[Ruby] [Rails] About helper method form_with [Basic]

2 minute read

I didn’t understand much during learning, so I would like to sort out the output. I will write carefully from the basics. If you point out, please.

What is a helper method?

To begin with, in rails, methods for making HTML tags appear in views and processing text are prepared in advance. These are called helper methods. form_with is a kind of helper method.

*Example of helper method Use of helper method form_tag Implementation of form on post page etc. link_to link implementation simple_format Automatically format posted text for easy viewing submit_tag Used when you want to add the submit function. text_field_tag etc,, It seems that you can make your own. [Reference article] https://qiita.com/Yukaaaah/items/19e524fd0c0e4a3451f1

About ##form_with This is a helper method for form implementation recommended from Rails 5.1 version. form_tag/form_for seems to be deprecated. (The description of these two methods is omitted.)

.erb


<!-- Example using form_tag -->
<%= form_tag('/posts', method: :post) do %>
  <input type="text" name="content">
  <input type="submit" value="Post">
<% end %>

.erb


<!-- Example using form_with -->
<%= form_with model: @post, local: true do |form| %>
  <%= form.text_field :content %>
  <%= form.submit'post' %>
<% end %>

The features of form_with are: ① It is not necessary to specify the HTTP method by automatically selecting the path ② The instance of the model that inherits ActiveRecord passed from the controller can be used (@post corresponds to it in the above)

Also in this case, ① For new posts ② When calling an existing post Will change the processing.

① For new posts

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

② When calling an existing post

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

Clicking the post button will send it to the update action.

Summary

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 judge whether there is content in @post of the model and send it.

Besides this You can pass multiple models, for example form_with model: [@￰post, @￰comment]. I would like to write it in another article…