--Use of form_with method properly --Handling of strong parameters associated with it --How to make form contents HTTP communication
$ rails -v
Rails 6.0.3.1
$ ruby -v
ruby 2.7.0p0 (2019-12-25 revision 647ee6f091) [x86_64-darwin19]
It is a method that builds UI parts for submitting forms, and has the feature of automatically switching controller actions on the server side.
The factors for switching vary depending on the values for the optional model and url, and are as follows.
option | @Contents of user | Action to be called | Use |
---|---|---|---|
model: @user | User.new | create | User created |
model: @user | User.find() | update | User edit |
url: sessions_path | create | User login |
Moreover, the difference between the options is as follows.
option | Input area name attribute | Strong parameters |
---|---|---|
model: @user | name="user[email]" | params.require(:user).permit(:email) |
url: users_path | name="email" | params.permit(:email) |
.erb
<%= form_with model: @user do |f| %>
<%= f.label :name, "name" %>
<%= f.text_field :name, placeholder: "Yamada" %>
<%= f.submit "sign up" %>
<% end %>
.erb
<%= form_with url: sessions_path do |f| %>
<%= f.label :name, "name" %>
<%= f.text_field :name, placeholder: "Yamada" %>
<%= f.submit "log in" %>
<% end %>
In fact, the remote: true
option is given by default, and it is preset to perform so-called Ajax communication.
Therefore, if nothing is set, flash may not be displayed because the render method is not executed.
The above problem can be solved by making the following settings in order to perform normal HTTP communication.
.erb
<%= form_with model: @user, local: true do |form| %>
form_with is convenient because it automatically determines the type of HTTP request.
Recommended Posts