Ruby on Rails:是"form_for(:product,...)"和"form_for(@product,...)"相等的? [英] Ruby on Rails: Are "form_for(:product, ...)" and "form_for(@product, ...)" equivalent?

查看:60
本文介绍了Ruby on Rails:是"form_for(:product,...)"和"form_for(@product,...)"相等的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<%= 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]" />

idname的值由: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 to create
  • 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆