1

我的观点如下

<%= 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][]'}) %>

我想改变这一点。上述列出了多选框中的所有值,如下所示 在此处输入图像描述

我想把它改成

在此处输入图像描述

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

编辑:

在此处输入图像描述

4

2 回答 2

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][]'})

你应该把它正确地放在一些助手中。如果有不清楚的地方,请随意询问集合查询,这非常复杂。

于 2013-06-14T08:37:29.543 回答
0

您可以使用来自 ActionView::Helpers::FormOptionsHelper 的 grouped_collection_select 帮助器

于 2013-06-14T07:30:14.993 回答