3

パーティごとにアクティブなプロジェクトをドロップダウン リストに表示しようとしています。active_projects は Party モデル内のメソッドです。以下の grouped_collection_select コードは機能しますが、フォームを simple_form に変換しようとすると、active_projects メソッドが認識されなくなります。

以下は、私の 2 つのコードの抜粋です。最初のものは正常に機能し、もう一方はエラーを引き起こします。

# rails default
<%= f.grouped_collection_select(:project_id, 
                                 Party.all, 
                                 :"active_projects(#{date.strftime("%Y%m%d")})", 
                                 :party_name, 
                                 :id, :project_name) %>
# simple form
<%= f.input :project_id, 
            collection: Party.all, as: :grouped_select,
            group_method: :"active_projects(#{date})" %>
4

1 に答える 1

0

これは少し古いことは知っていますが、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 プロパティで渡します。親コレクションの取得には使用されませんが、後でクラス インスタンスで使用するために格納されているだけです。このようにして、そのクラスで別のメソッドを呼び出すと、子でフィルタリングを行うために必要な値が含まれます。

于 2015-10-31T02:03:27.753 に答える