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

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

Is

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

and

<         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-06 13:35

    Similar, but not the same. When you use @product you have the benefit of being able to automatically populate values to the form fields from the model instance.

    For example, if you in the action :new in your Controller assign @product like this:

    @product = Product.new
    

    Then there will probably not be any difference in the generated form. However, if you follow this up in you :create action like this:

    @product = Product.new(params[:product])
    if @product.save
      ...
    else
      render :action => :new
    end
    

    Then if it is unable to save the @product instance, then it will render the same form as in :new but this time have all the fields populated with the values posted. That would not have been possible if you used :product

提交回复
热议问题