Ruby on Rails Collection选择 – 如何预先选择正确的值?

我花了最后三天的时间来处理我的“列表” – 表单的集合_选择表单助手,用户可以在其中选择一个类别。

我想将listing.category_id中当前设置的类别作为预选值。

我的视图代码如下所示:

 10, :selected => @listing.category_id.to_s})%> 

我知道这是不正确的,但即使阅读Shiningthrough( http://shiningthrough.co.uk/blog/show/6 )的解释,我也无法理解如何继续。

感谢您的支持,

迈克尔

查看:如上所述
控制器:

 def categories #Step 2 @listing = Listing.find(params[:listing_id]) @seller = Seller.find(@listing.seller_id) @category = Category.find(:all) @listing.complete = "step1" respond_to do |format| if @listing.update_attributes(params[:listing]) flash[:notice] = 'Step one succesful. Item saved.' format.html #categories.html.erb end end end 

collection_select不支持所选选项,事实上,它不需要它。 它会自动选择其值与表单构建器对象的值匹配的选项。

让我举个例子。 假设每个post属于一个类别。

 @post = Post.new <% form_for @post do |f| %>  <%= f.collection_select :category_id, Category.all, :id, :name, :prompt => true %> <% end %> @post = Post.new(:category_id => 5) <% form_for @post do |f| %>  <%= f.collection_select :category_id, Category.all, :id, :name, :prompt => true %> <% end %> 

编辑

我建议使用代表性变量名称。 使用@categories而不是@category。 :)此外,从只读视图中拆分更新逻辑。

 def categories #Step 2 @listing = Listing.find(params[:listing_id]) @seller = Seller.find(@listing.seller_id) @categories = Category.find(:all) @listing.complete = "step1" respond_to do |format| if @listing.update_attributes(params[:listing]) flash[:notice] = 'Step one succesful. Item saved.' format.html #categories.html.erb end end end <% form_for @listing do |f| %> <%= f.collection_select :category_id, @categories, :id, :name, :prompt => true %> <% end %> 

如果它不起作用(即它选择提示),则表示您没有与该记录关联的category_id或者Category集合为空。 在将对象传递给表单之前,请确保不要为某个地方的@listing重置category_id的值。

编辑2:

 class Category def id_as_string id.to_s end end <%= f.collection_select :category_id, Category.all, :id_as_string, :name, :prompt => true %> 

我的category_id在数据库中保存为字符串,但比较在整数值之间。

 if @listing.category_id != "" @listing.category_id = @listing.category_id.to_i end 

这解决了它 – 现在预先选择了正确的值。