I didn't understand much during the study, so I would like to organize it while outputting it. I will write carefully from the basics. If you point out, please.
In the first place, rails has a method for making HTML tags appear in view and processing text in advance. These are called helper methods. form_with is a type of helper method.
A helper method for form implementation that has been recommended since the version Rails 5.1. form_tag / form_for seems to be deprecated. (The explanation of these two methods is omitted.)
.erb
<!-- form_Example using tag-->
<%= form_tag('/posts', method: :post) do %>
<input type="text" name="content">
<input type="submit" value="Post">
<% end %>
.erb
<!--form_Example using with-->
<%= form_with model: @post, local: true do |form| %>
<%= form.text_field :content %>
<%= form.submit 'Post' %>
<% end %>
The feature of form_with is (1) The path is automatically selected and there is no need to specify the HTTP method. (2) An instance of the model that inherits ActiveRecord passed from the controller can be used (@post corresponds to that in the above)
In this case, ① For new posts ② When calling an existing post The processing will change with.
posts_controller.rb
def new
@post = Post.new
end
Click the post button and it will be sent to the create action.
new.html.erb
<%= form_with model: @post, class: :form, local: true do |form| %>
<%= form.text_field :title, placeholder: :title, class: :form__title %>
<%= form.text_area :content, placeholder: :Blog body, class: :form__text %>
<%= form.submit 'Post', class: :form__btn %>
<% end %>
posts_controller.rb
def edit
@post = Post.find(params[:id])
end
edit.html.erb
<%= form_with model: @post, class: :form, local: true do |form| %>
<%= form.text_field :title, placeholder: :title, class: :form__title %>
<%= form.text_area :content, placeholder: :Blog body, class: :form__text %>
<%= form.submit 'Post', class: :form__btn %>
<% end %>
Click the post button and it will be sent to the update action.
By comparison, the form parts of new.html.erb and edit.html.erb are the same! !! !! Therefore, the form part can be made into a partial template and the amount of description can be reduced. It will automatically determine if the model @post has contents and send it to you.
Besides this You can pass multiple models, for example form_with model: [@post, @comment]. I would like to write it in another article ...
Recommended Posts