[Ruby] [Rails] I fully understood form_with

1 minute read

Content of this article

  • Different use of form_with method
  • Handling of strong parameters accordingly
  • How to make form contents HTTP communication

environment

$ rails -v
Rails 6.0.3.1
$ ruby -v
ruby 2.7.0p0 (2019-12-25 revision 647ee6f091) [x86_64-darwin19]

What is #form_with

It is a method that builds a UI component for submitting a form, and has the feature of automatically switching the controller action on the server side.

The factors that cause switching depend on the values for the optional model and url, and are as follows.

Options Contents of @user Action to be invoked Purpose
model: @user User.new create Create user
model: @user User.find() update User edit
url: sessions_path   create User login

In addition, the differences between the options are as follows.

Option Input area name attribute Strong parameter
model: @user name=”user[email]” params.require(:user).permit(:email)
url: users_path name=”email” params.permit(:email)

Example using the ##model option

.erb


<%= form_with model: @user do |f| %>
  <%= f.label :name, "name" %>
  <%= f.text_field :name, placeholder: "Yamada" %>

  <%= f.submit "register" %>
<% end %>

Example using the ##url option

.erb


<%= form_with url: sessions_path do |f| %>
  <%= f.label :name, "name" %>
  <%= f.text_field :name, placeholder: "Yamada" %>

  <%= f.submit "login" %>
<% end %>

local option

Actually, the ```remote: true

option is added by default, and it is set in advance to perform so-called Ajax communication.


Therefore, if nothing is set, flash may not be displayed because the render method is not performed.

In order to perform normal HTTP communication, the above problems can be solved by making the following settings.


#### **`.erb`**

<%= form_with model: @user, local: true do |form| %> ```

Summary

form_with is convenient because it automatically determines the type of HTTP request.