繁体   English   中英

使用Active Admin设置has_many过滤器

[英]Setting up a has_many through filter with Active Admin

我试图简单地允许在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,但没有什么可行的。

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

在某些时候has_many / through比habtm更灵活(你可以有其他字段等)

你为什么不用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

这里的答案可以在这里找到,前提是你可以在sql中编写你的有很多!

如何向Active Admin添加自定义过滤器?

我也在寻找相同的工作解决方案,如下所示。 在这里发布,以便将来可以帮助其他人。

应用程序/管理/ location.rb

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

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

希望能帮助到你..!!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM