Hopefully this is just a quicky....
希望这只是一个罢工....
I have a form to edit a product and each product belongs to a category. In the form_for(@product) I can populate a select box for the categories in a couple of ways:
我有一个编辑产品的表单,每个产品都属于一个类别。在form_for(@product)中,我可以通过以下几种方式填充类别的选择框:
<%= f.select :category_id, Category.find(:all).collect{|c| [c.category, c.id]}, :prompt => "Pick a Category" %>
or:
或者:
<%= f.select :category_id, options_from_collection_for_select(Category.find(:all), :id, :category) %>
The first option remembers the category when editing the product, the second option doesn't. Can anybody enlighten me as to why? Is there a way to use the options_from_collection_for_select in this scenario and have it remember the category upon editing?
第一个选项在编辑产品时记住类别,第二个选项不记得。有人能告诉我为什么吗?是否有一种方法可以在这个场景中使用options_from_collection_for_select,并让它在编辑时记住类别?
Cheers, Adam
干杯,亚当
3 个解决方案
#1
4
The Codeglot's answer should have been:
Codeglot的答案应该是:
<%= f.collection_select :category_id, Category.all, :id , :name %>
(See Rails: undefined method `map' for Ingredient for explanation)
(参见Rails:解释成分的未定义方法“map”)
#2
1
<%= f.collection_select :category_id, Category, :id , :name %>
make sure you change :name
to the field that you want displayed. It's probably :name
or :title
确保您将:name更改为要显示的字段。可能是:姓名或头衔。
#3
0
Try this:
试试这个:
<%= f.select :category_id, options_from_collection_for_select(Category.find(:all), :id, :category, params[:category_id].to_i) %>
#1
4
The Codeglot's answer should have been:
Codeglot的答案应该是:
<%= f.collection_select :category_id, Category.all, :id , :name %>
(See Rails: undefined method `map' for Ingredient for explanation)
(参见Rails:解释成分的未定义方法“map”)
#2
1
<%= f.collection_select :category_id, Category, :id , :name %>
make sure you change :name
to the field that you want displayed. It's probably :name
or :title
确保您将:name更改为要显示的字段。可能是:姓名或头衔。
#3
0
Try this:
试试这个:
<%= f.select :category_id, options_from_collection_for_select(Category.find(:all), :id, :category, params[:category_id].to_i) %>