5

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

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

完全相同的 ?

4

3 回答 3

5

帮助程序中的@productinform_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]" />

idandname值由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 和输入字段的值。

于 2010-12-14T07:47:46.620 回答
2

类似,但不一样。当您使用 @product 时,您可以从模型实例中自动将值填充到表单字段中。

例如,如果您在控制器中的操作 :new 中分配 @product,如下所示:

@product = Product.new

那么生成的表单可能不会有任何差异。但是,如果您在 :create 中跟进此操作,如下所示:

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

然后,如果它无法保存 @product 实例,那么它将呈现与 :new 中相同的表单,但这次将使用发布的值填充所有字段。如果您使用 :product ,那将是不可能的

于 2010-12-14T07:34:54.810 回答
1

form_for你到那里已经很长时间了。对您的问题的简短回答:@product对于确定对可以具有许多对象的资源执行什么操作很有用,这听起来像。:product另一方面,总是会采取相同的行动,update。这最适用于单一资源。可以在路由指南中找到对资源的​​详细说明。入门指南中也对此进行了说明。

你的第二个form_for可能会缩短到这个:

<%= form_for @product do |f| %>
   ...
<% end %>

路由和入门指南中解释了所有内容。

另外,我在你的个人资料中看到你来自墨尔本。Ruby on Rails Oceania Google 小组列出了全国各地的聚会。墨尔本每个月都会举办一次,您可能想参加一次,结识志同道合的人。

于 2010-12-14T08:13:54.040 回答