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

Mic*_*itz 7 ruby ruby-on-rails

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

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

我的视图代码如下所示:

<%= l.collection_select(:category_id, @category, :id, :name, options = {},
                        html_options = {:size => 10, :selected => @listing.category_id.to_s})%>
Run Code Online (Sandbox Code Playgroud)

我知道这是不正确的,但即使阅读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
Run Code Online (Sandbox Code Playgroud)

Sim*_*tti 12

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

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

@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 %>
Run Code Online (Sandbox Code Playgroud)

编辑:

我建议使用代表性的变量名.使用@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 %>
Run Code Online (Sandbox Code Playgroud)

如果它不起作用(即它选择提示),则表示您没有与该记录关联的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  %>
Run Code Online (Sandbox Code Playgroud)