如何在Rails的groups_options_for_select中设置selected_key?

时间:2015-11-05 02:55:10

标签: html ruby-on-rails ruby ruby-on-rails-4 drop-down-menu

我有这个用于我的下拉列表:

<%= select_tag 'daily_order[kitchen_id]', grouped_options_for_select(Kitchen.for_normal_and_atworld_kitchens_select, selected_key = :id, options = {}), class: "form-control", onchange: "kitchen_change()" %>

但是当我通过selected_key时,:id无效。

当我像这样硬编码时:

<%= select_tag 'daily_order[kitchen_id]', grouped_options_for_select(Kitchen.for_normal_and_atworld_kitchens_select, selected_key = 5, options = {}), class: "form-control", onchange: "kitchen_change()" %>

它工作正常。

我的厨房模型:

def self.for_normal_and_atworld_kitchens_select
    {
      'Normal Kitchens' => where(special_kitchen: false, atworld: false).where.not(id: @exclude_kitchens).map {|x| [x.name, x.id]},
      'Around The World Kitchens' => where(special_kitchen: false, atworld: true).where.not(id: @exclude_kitchens).map {|x| [x.name, x.id]}
    }
  end

我现在该怎么做才能使grouped_options_for_select selected_key正常工作?

注意

@exclude_kitchens是一系列厨房ID,如[1,2,3]。它返回正确的输出并在项目的其他地方正常工作。

1 个答案:

答案 0 :(得分:0)

符号:id应该代表什么?您必须传递一个或多个要选择的值。看看doc

您需要以某种方式动态获取ID的副本,例如@exclude_kitchens.first或任何有意义的事情。