3

我试图简单地允许在 ActiveAdmin 的位置页面上过滤类别。

我有三个模型:

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>

我试过过滤器:类别,过滤器:categories_locations,但没有任何效果。

有没有人经历过这个——有人有解决方案吗?

4

4 回答 4

2

我也在寻找相同的解决方案,并找到了如下的工作解决方案。在这里发帖,以便将来对其他人有所帮助。

应用程序/管理员/位置.rb

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

应用程序/模型/位置.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

at some point has_many/through is more flexible than habtm (you can have additional fields etc)

于 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 回答