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

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

我想将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

解决方法

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

让我举个例子.假设每个帖子属于一个类别.

@post = Post.new

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

编辑:

我建议使用代表性变量名称.使用@categories而不是@category.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...