[Rails] Completely understand form_with

Content of this article

--Use of form_with method properly --Handling of strong parameters associated with it --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 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)

Example using the model option

.erb


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

  <%= f.submit "sign up" %>
<% 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 "log in" %>
<% end %>

local option

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| %>

Summary

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

Recommended Posts

[Rails] Completely understand form_with
[Rails] form_with
Understand Rails "shallow" routing
Understand migration in rails
Delve into Rails form_with
Understand the helper method form_with
[Rails] Two ways to write form_with
[Rails] Learn yield to understand content_for
Rails form_with communicates Ajax by default
[Rails] About helper method form_with [Basic]
[Introduction to Rails] form_with (local: true)
[Rails] Articles for beginners to organize and understand the flow of form_with
[Form with two arguments] rails, form_for / form_with arguments
[Rails] About local: true described in form_with