如何根据类别分离多个选择框值并显示为组?

时间:2013-06-14 07:17:40

标签: ruby-on-rails ruby-on-rails-3 multi-select

我的观点中有以下内容

<%= collection_select(:thing, :free_things_ids, FreeThings.where(:shop_id => current_user.shop_id).all(:order =>'name ASC'), :id, :name, {:include_blank => '----Select----'}, {:multiple => true, :size => 10, :name=>'thing[free_things_ids][]'}) %>

我想改变这个。上面列出了多选框中的所有值,如下所示 enter image description here

我希望将其更改为

enter image description here

这是基于category_id分开的。那我该怎么做呢?请帮帮我。

修改

enter image description here

2 个答案:

答案 0 :(得分:1)

您可以使用grouped_collection_select,例如:

<%= collection_select(:thing, :free_things_ids, Categories.all, 
                      :free_things, :name, :id, :name, 
                      {:include_blank => '----Select----'}, 
                      {:multiple => true, :size => 10, 
                      :name=>'thing[free_things_ids][]'})

然而,这将获取所有FreeThings。如果您想查询where(:shop_id => current_user.shop_id),则必须执行更复杂的操作,例如:

collection = FreeThings.where(:shop_id => current_user.shop_id).order('name ASC')
               .group_by{|f| f.category.name} # Groups the free things collection by the associated category's name
               .map{|category_name, free_things| [category_name, free_things.map{|free_thing| [free_thing.name, free_thing.id]} } # Creates a set (array) of name and id of each free_thing for each group
# This would give a nested array like this:
# [
#   ["Cat 1", [
#     ["Thi 1", 1], ["Thi 2", 2], ["Thi 3", 2]
#   ],
#   ["Cat 2", [
#     ["Thi 5", 5], ["Thi 6", 6], ["Thi 7", 7]
#   ],
#   ...
# ]
selected = @thing.free_things.map(&:id) # This is the selected items, should be a array of ids


<%= select(:thing, :free_things_ids,  
           grouped_options_for_select(collection, selected),
           {:include_blank => '----Select----'}, 
           {:multiple => true, :size => 10, :name=>'thing[free_things_ids][]'})

你应该把它妥善地放在一些帮助器里。如果有不清楚的东西,请随意询问收集查询,这非常复杂。

答案 1 :(得分:0)

您可以使用ActionView :: Helpers :: FormOptionsHelper中的grouped_collection_select帮助器。