Ruby on Rails: Are “form_for(:product, …)” and “form_for(@product, …)” equivalent?

前端 未结 3 507
囚心锁ツ
囚心锁ツ 2021-02-06 13:09

Is

<%= form_for(:product, :url => {:action => \'update\', :id => @product.id})) do |f| %>
  ...
<% end %>

and

<         


        
3条回答
  •  一整个雨季
    2021-02-06 13:23

    The @product in the form_for helper ships with more features.

    The :product only affects the input field's id and name. For example you have a text filed in the form:

    <%= form_for :product, :url => {...} do |f| %>
      <%= f.text_field :price %>
    <% end %>
    

    The generated html would look like:

    
    

    The id and name value is determined by the :product.to_s and the text field name.

    While if you use @product, the :url is not necessary because the url would be determined according to the @product's status:

    • if the @product is a new record, the url would post to create
    • otherwise, the url would post to update

    And the input filed's id and name is affected by @product's class name, so it's important when you're using single table inheritant. The input filed's value is automatically assigned with the @product's attribute value. So if you use @product, the html output would look like:

    
    

    Assume the @product's class name is Item, then the output would change to:

    
    

    And of course you can use both of :product and @product:

    <%= form_for :product, @product do |f| %>
    

    The :product controls input filed's name and id, and the @product controls the url and input field's value.

提交回复
热议问题