Ruby on Rails:是"form_for(:product,...)"和"form_for(@product,...)"相等的? [英] Ruby on Rails: Are "form_for(:product, ...)" and "form_for(@product, ...)" equivalent?
问题描述
是
<%= form_for(:product, :url => {:action => 'update', :id => @product.id})) do |f| %>
...
<% end %>
和
<%= form_for(@product, :url => {:action => 'update', :id => @product.id})) do |f| %>
...
<% end %>
完全一样吗?
推荐答案
form_for
帮助器中的@product
具有更多功能.
The @product
in the form_for
helper ships with more features.
:product
仅影响输入字段的ID和名称.例如,您有以下格式的文本:
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 %>
生成的html看起来像:
The generated html would look like:
<input type="text" id="product_price" name="product[price]" />
id
和name
的值由:product.to_s
和文本字段名称确定.
The id
and name
value is determined by the :product.to_s
and the text field name.
如果使用@product
,则不需要:url
,因为该URL将根据@product
的状态确定:
While if you use @product
, the :url
is not necessary because the url would be determined according to the @product
's status:
- 如果
@product
是新记录,则该网址将发布到create
- 否则,该网址将发布到
update
- if the
@product
is a new record, the url would post tocreate
- otherwise, the url would post to
update
,输入文件的ID和名称受@product
的类名影响,因此在使用单个表继承者时,这一点很重要.输入字段的值会自动分配@product
的属性值.因此,如果您使用@product
,则html输出将如下所示:
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:
<input type="text" id="product_price" name="product[price]" value="some value" />
假设@product
的类名是Item
,则输出将更改为:
Assume the @product
's class name is Item
, then the output would change to:
<input type="text" id="item_price" name="item[price]" value="some value" />
当然可以同时使用:product
和@product
:
<%= form_for :product, @product do |f| %>
:product
控制输入文件的名称和ID,而@product
控制URL和输入字段的值.
The :product
controls input filed's name and id, and the @product
controls the url and input field's value.
这篇关于Ruby on Rails:是"form_for(:product,...)"和"form_for(@product,...)"相等的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!