草庐IT

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

coder 2025-06-21 原文

过去三天,我一直在为我的“列表”收集 _ 选择表单助手 - 表单,用户可以在其中选择类别。

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

我的 View 代码如下所示:

<%= 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 ) 的解释,我也无法理解如何进行。

感谢您的支持,

迈克尔

查看: 如上
Controller :

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, :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。 :) 另外,将更新逻辑从只读 View 中分离出来。

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,或者类别集合为空。在将对象传递给表单之前,请确保不要在某处重置 @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  %>

关于ruby-on-rails - Ruby on Rails Collection select - 如何预选正确的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1065318/

有关ruby-on-rails - Ruby on Rails Collection select - 如何预选正确的值?的更多相关文章

随机推荐