1

我正在尝试使用 collection_select 方法创建一个 <select> 元素,但似乎为了选择正确的 <option>,传递给 collection_select 的标识符需要是实例变量而不是局部变量(这部分发生)。

categories因此,当我为a创建 <select> 时product,默认情况下不会选择正确的类别。

_product_row.erb(不工作):

My product: <%= product.name %>
<%= collection_select(:product, :category_id, @current_user.categories, :id, :name, options = {:prompt => "-- Select a category --"}) %>

截屏:

替代文字 http://img534.imageshack.us/img534/8929/screenshot20100421at120.png

我发现我可以通过事先声明一个实例变量来让它工作,但这对我来说似乎是一个巨大的黑客攻击。

_product_row.erb(工作):

<% @product_select_tmp = product %>
<%= collection_select(:product_select_tmp, :category_id, @current_user.categories, :id, :name, options = {:prompt => "-- Select a category --"}) %>

截屏:

替代文字 http://img534.imageshack.us/img534/1958/screenshot20100421at120l.png

因为这个部分是对产品集合的迭代,所以我不能只在控制器中声明@product(IOW,除非我遗漏了一些东西,product必须是这个部分中的局部变量)。

那么如何让collection_select在使用局部变量调用它时选择适当的项目呢?

4

2 回答 2

2

您是否尝试过在:selected选项哈希中传递密钥?如果您为它提供电流product.id,它应该按照您期望的方式运行。

<%= collection_select(:product, :category_id, @current_user.categories, :id, :name, {:prompt => "-- Select a category --", :selected => product.category.id}) %>

于 2010-04-21T17:24:39.223 回答
1

您可以将集合传递给局部变量并指定一个局部变量以将它们传递为:

<%= render :partial => "products/product_row", :collection => @products, :as => :products %>

相关文档:http ://apidock.com/rails/ActionView/Partials

于 2010-04-20T17:43:09.780 回答