您可以使用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][]'})
你应该把它正确地放在一些助手中。如果有不清楚的地方,请随意询问集合查询,这非常复杂。