是
<%= 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, :url => {:action => 'update', :id => @product.id})) do |f| %>
...
<% end %>
和
<%= form_for(@product, :url => {:action => 'update', :id => @product.id})) do |f| %>
...
<% end %>
完全相同的 ?
帮助程序中的@product
inform_for
具有更多功能。
:product
唯一影响输入字段的 id 和 name 。例如,您在表单中提交了一个文本:
<%= form_for :product, :url => {...} do |f| %>
<%= f.text_field :price %>
<% end %>
生成的 html 如下所示:
<input type="text" id="product_price" name="product[price]" />
id
andname
值由and:product.to_s
文本字段名称确定。
如果使用@product
,:url
则不需要,因为 url 将根据@product
的状态确定:
@product
是新记录,则 url 将发布到create
update
并且输入字段的 id 和 name 受@product
类名的影响,因此在使用单表继承时很重要。输入字段的值自动分配有@product
的属性值。因此,如果您使用@product
,则 html 输出将如下所示:
<input type="text" id="product_price" name="product[price]" value="some value" />
假设@product
的类名是Item
,那么输出将变为:
<input type="text" id="item_price" name="item[price]" value="some value" />
当然,您可以同时使用:product
和@product
:
<%= form_for :product, @product do |f| %>
控件输入字段的:product
名称和 id,@product
控件 url 和输入字段的值。
类似,但不一样。当您使用 @product 时,您可以从模型实例中自动将值填充到表单字段中。
例如,如果您在控制器中的操作 :new 中分配 @product,如下所示:
@product = Product.new
那么生成的表单可能不会有任何差异。但是,如果您在 :create 中跟进此操作,如下所示:
@product = Product.new(params[:product])
if @product.save
...
else
render :action => :new
end
然后,如果它无法保存 @product 实例,那么它将呈现与 :new 中相同的表单,但这次将使用发布的值填充所有字段。如果您使用 :product ,那将是不可能的
form_for
你到那里已经很长时间了。对您的问题的简短回答:@product
对于确定对可以具有许多对象的资源执行什么操作很有用,这听起来像。:product
另一方面,总是会采取相同的行动,update
。这最适用于单一资源。可以在路由指南中找到对资源的详细说明。入门指南中也对此进行了说明。
你的第二个form_for
可能会缩短到这个:
<%= form_for @product do |f| %>
...
<% end %>
路由和入门指南中解释了所有内容。
另外,我在你的个人资料中看到你来自墨尔本。Ruby on Rails Oceania Google 小组列出了全国各地的聚会。墨尔本每个月都会举办一次,您可能想参加一次,结识志同道合的人。