3

ActiveAdminの[場所]ページでカテゴリのフィルタリングを許可しようとしています。

私は3つのモデルを持っています:

class Location < ActiveRecord::Base
  has_many :categories_locations
  has_many :categories, :through => :categories_locations

class CategoriesLocation < ActiveRecord::Base
    belongs_to :category
    belongs_to :location
end

class Category < ActiveRecord::Base
    has_many :categories_locations
    has_many :locations, :through => :categories_locations
end

私の場所のページでは、次のフィルターを使用しています。

ActiveAdmin.register Location do
  filter :name
  filter :category, :collection => proc { Category.all }, :as => :select

ただし、エラーが発生し続けます。

undefined method `category_eq' for #<MetaSearch::Searches::Location:0x007fd4f9b965d8>

filter:categories、filter:categories_locationsを試しましたが、何も機能しません。

誰かがこれを経験したことがあります-誰かが解決策を持っていますか?

4

4 に答える 4

2

私も同じものを探していて、以下のような実用的な解決策を見つけました。将来他の人に役立つかもしれないので、ここに投稿してください。

app / admin / location.rb

ActiveAdmin.register Location do
  filter :filter_by_category, label: 'Category', as: :select, collection: Category.pluck(:name, :id)

app / model / location.rb

class Location < ActiveRecord::Base
  has_many :categories_locations
  has_many :categories, :through => :categories_locations

  def self.filter_by_category(category_id)
    category_id = 1 if category_id == true # this is required only for id=1, ActiveAdmin return it as `true`
    joins(:categories).where("categories.id = ?", category_id)
  end

  #  Add your custom method as ransack 
  def self.ransackable_scopes(_auth_object = nil)
    [:filter_by_category]
  end
end

それが役に立てば幸い..!!

于 2019-02-14T06:30:47.513 に答える
1

ある時点で、has_many / throughはhabtmよりも柔軟性があります(追加のフィールドなどを持つことができます)

于 2012-05-31T08:15:12.310 に答える
0

これに対する答えは、SQLで多くの情報を記述できる場合に、ここで見つけることができます。

Active Adminにカスタムフィルターを追加するにはどうすればよいですか?

于 2014-10-07T09:17:25.260 に答える
-1

なぜあなたはhabtmを使わないのですか?

class Location < ActiveRecord::Base
  has_and_belongs_to_many :categories

class CategoriesLocation < ActiveRecord::Base
end

class Category < ActiveRecord::Base
    has_and_belongs_to_many :locations
end

その後

ActiveAdmin.register Location do
  filter :name
  filter :category_id, :collection => proc { Category.all }, :as => :select
于 2012-05-07T22:49:02.033 に答える