【问题标题】:Ruby on Rails Collection select - how to pre-select the right value?Ruby on Rails Collection select - 如何预先选择正确的值?
【发布时间】:2009-06-30 18:46:12
【问题描述】:

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

我希望将当前在 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

【问题讨论】:

标签: ruby-on-rails ruby


【解决方案1】:

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 的值。

编辑 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  %>

【讨论】:

  • 您好 weppos,感谢您的快速和良好的回答。我希望 collection_select 表现得像这样,不幸的是,在我的情况下它不会像这样表现。每当我将 @listing.category_id = 2 插入我的控制器时,我都会以我想要的方式获得预选字段。即使我根据参数得到了@listing = Listing.find... 并且该值确实是在数据库中设置的,但这不起作用。老实说,我迷路了。
  • 您能否发布一个完整的示例,包括控制器操作和视图?
  • 三年过去了,我才回来看答案,对我来说就是那么好。谢谢你,西蒙娜!
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    相关资源
    最近更新 更多