Click here for the other day's article New engineer who will be one serving in 100 days (3rd day)
Good evening. The weekend is over as soon as possible. I will update it today as well. I haven't written much about Rails so far Today I'm going to write about Rails Form.
I learned that there are several types. It's a good opportunity, so I'll try to put it together.
form_for form_tag form_with
These three. For the time being, try writing as you were told in the Tutorial I felt like it worked, but I thought it wouldn't work, so I'll look at it one by one.
form_for If a related model is prepared, pass the model with form_for.
<%= form_for @user do |form| # @Passing an instance variable called user%>
<%= form.text_field :email #Use the form created from the received model%>
<%= form.submit %>
<% end %>
In this case the associated model is @user It means that this model is linked to the form.
form_tag If there is no relevant model
<%= form_tag users_path do # user_Passing a URI called path%>
<%= text_field_tag :email %>
<%= submit_tag %>
<% end %>
Something like this. I am passing the url to the form in the form of users_path. This means that you are sending parameters.
form_with Well, you need to use two properly. The format of this form was created by saying that. Both are supported. So in Rails 5.1 and later, it seems that form should basically use this (that's right ...)
For example, if there is a related model (form_for above)
<%= form_with model: @user do |form| %>
<%= form.text_field :email %>
<%= form.submit %>
<% end %>
If there is no relevant model
<%= form_with url: users_path do |form| %>
<%= form.text_field :email %>
<%= form.submit %>
<% end %>
I see. It can be used in one format. Also, if URL: @user exists in the DB, it jumps to the update action, otherwise it jumps to the create action. In other words, the form will judge whether it is POST or PATCH and send it.
This is amazing. I was surprised when I was doing Java!
<%= form_with model: @user, local: true do |form| %>
<%= form.text_field :email %>
<%= form.check_box :send_welcome_email %>
<%= form.submit %>
<% end %>
In the above, this: send_welcome_email does not support the @user model, Still no problem. The value can be retrieved with params [: user] [: send_welcome_email]
<%= form_with model: @user, local: true %>
<% end %>
local: true isn't it? I had a question, so I looked it up.
In form_with, communication with ajax is performed in the default state. The option to cancel it is local: true What did you say. Hmm. I'm not sure about it, so I'll review it here.
For the time being, I wrote the basics of form. Basically, it seems that you should go with form_with. After that, I will read the reference and deepen my knowledge.
that's all
** 96 days to become a full-fledged engineer **
Recommended Posts