我尝试设置Rails 4表单以显示collection_select
中的所有不同商店分支,然后显示grouped_collection_select
显示每个存储类型的所有可能组合科。然后我想过滤掉使用CoffeeScript在某个分支上不可用的存储类型,如Railscasts #88所示(这不是问题)
但是,我无法弄清楚如何填充分组选择预过滤。我需要通过加入表StorageTypeBranch
来查找每个分支的可用存储类型。
我的模特:
class StorageType < ActiveRecord::Base
has_many :storage_type_branches
has_many :branches, through: :storage_type_branches
end
class Branch < ActiveRecord::Base
has_many :storage_type_branches
has_many :storage_types, through: :storage_type_branches
end
# Joining table
class StorageTypeBranch < ActiveRecord::Base
belongs_to :storage_type
belongs_to :branch
end
控制器:
def new
@branches = Branch.where(is_active: true).order(:name)
# Doesn't work because it has to be called on one instance of the model.
# What should this be?
@storage_types = @branches.storage_types.all
end
查看:
<%= f.label :branch_id %>
<%= f.collection_select :branch_id, @branches, :id, :name, prompt: '<--- Select a Branch --->' %>
<br/>
<%= f.label :storage_type_id %>
# Where I want the grouped select to be
<%= f.grouped_collection_select @storage_types %>
我希望实现的最终结果:
真的很感激任何帮助。
答案 0 :(得分:2)
如果您想要分支列表的所有分支类型:
@storage_types = @branches.flat_map{|branch| branch.storage_types}.uniq # Array
如果你想要每个分支:
@storage_types = Hash[@branches.map{|branch| [branch, branch.storage_types]}]
# {branch1 => [storage_typeA, storage_typeB], branch2 => [storage_typeC, storageTypeE]}
然后,您可以使用以下内容对集合进行分组:
<%= f.input :storage_types, :as => :grouped_select, :collection => @storage_types, :group_method => :first, :group_label_method => :last %>
有关更多替代方案,请参阅:simple_form: how to create a grouped select box?