これは少し古いことは知っていますが、simple_form を使用してこの問題を解決できます。それが最善の解決策かどうかはわかりませんが、うまくいきます。
基本的に、問題は group_method に値を渡すことに帰着します。私の場合、彼/彼女が所属する current_users 会社を取得する必要があるクラスがありました。私のモデル/データベース構造は次のようなものでした:
タイプ -> カテゴリ
私の場合、Type レコードはグローバルで、特定の会社に属していませんでした。ただし、カテゴリ モデル レコードは特定の会社に属していました。目標は、グループ化された選択をグローバル タイプで表示し、次にその下に会社固有のカテゴリを表示することです。これが私がしたことです:
class Type < ActiveRecord::Base
has_many :categories
attr_accessor :company_id
# Basically returns all the 'type' records but before doing so sets the
# company_id attribute based on the value passed. This is possible because
# simple_form uses the same instance of the parent class to call the
# group_by method on.
def self.all_with_company(company_id)
Type.all.each do |item|
item.company_id = company_id
end
end
# Then for my group_by method I added a where clause that reuses the
# attribute set when I originally grabbed the records from the model.
def categories_for_company
self.categories.where(:company_id => self.company_id)
end
end
したがって、上記は型クラスの定義です。参考までに、私のカテゴリ クラスの定義を次に示します。
class Category < ActiveRecord::Base
belongs_to :company
belongs_to :type
end
次に、simple_form コントロールで次のようにしました。
<%= f.association :category, :label => 'Category', :as => :grouped_select, :collection => Type.all_with_company(company_id), :group_method => :categories_for_company, :label_method => :name %>
基本的に、:group_method プロパティでフィルタリングしたい値を渡す代わりに、:collection プロパティで渡します。親コレクションの取得には使用されませんが、後でクラス インスタンスで使用するために格納されているだけです。このようにして、そのクラスで別のメソッドを呼び出すと、子でフィルタリングを行うために必要な値が含まれます。