Ruby on Rails集合选择 - 如何预先选择正确的值?

8

我过去三天一直在为我的“列表”表单开发 _ 选择表单助手集合,让用户可以选择一个类别。

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

我的视图代码如下:

<%= l.collection_select(:category_id, @category, :id, :name, options = {},
                        html_options = {:size => 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

Rails中如何在ActionView助手的collection_select中预选一个值? - John Topley
我在原来的答案中添加了一个可能的解决方案。 - Simone Carletti
2个回答

14

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

让我举个例子。假设每篇文章都属于一个类别。

@post = Post.new

<% form_for @post do |f| %>
  <!-- no option selected -->
  <%= f.collection_select :category_id, Category.all, :id, :name, :prompt => true  %>
<% end %>

@post = Post.new(:category_id => 5)

<% form_for @post do |f| %>
  <!-- option with id == 5 is selected -->
  <%= 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的值。
class Category
  def id_as_string
    id.to_s
  end
end

<%= f.collection_select :category_id, Category.all, :id_as_string, :name, :prompt => true  %>

嗨weppos,感谢您的快速和好的回答。我期望collection_select能够像这样运行,但不幸的是,在我的情况下它并没有像这样运行。每当我在控制器中插入 @listing.category_id = 2 时,我得到了我想要的预选字段。即使我基于params得到了@listing = Listing.find...,并且该值确实在数据库中设置了,但这并不起作用。说实话,我很迷茫。 - Michael Schmitz
你能贴出一个完整的示例,包括控制器操作和视图吗? - Simone Carletti
三年过去了,我又回来看这个答案了。对我来说真的很有用。谢谢你,Simone! - Michael Schmitz

1

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

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

这解决了 - 现在正确的值被预先选择。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接