[英]Setting up a has_many through filter with Active Admin
I'm trying to simply allow filtering of categories on the Locations page for ActiveAdmin. 我试图简单地允许在ActiveAdmin的“位置”页面上过滤类别。
I have three models: 我有三个型号:
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
On my locations page, I'm using this filter: 在我的位置页面上,我正在使用此过滤器:
ActiveAdmin.register Location do
filter :name
filter :category, :collection => proc { Category.all }, :as => :select
However, it keeps throwing an error. 但是,它不断抛出错误。
undefined method `category_eq' for #<MetaSearch::Searches::Location:0x007fd4f9b965d8>
I've tried filter :categories, filter :categories_locations, but nothing will work. 我尝试过滤:类别,过滤:categories_locations,但没有什么可行的。
Has anyone experienced this –– anyone have a solution? 有没有人经历过这个 - 有人有解决方案吗?
在某些时候has_many / through比habtm更灵活(你可以有其他字段等)
why aren't you using 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
and then 接着
ActiveAdmin.register Location do
filter :name
filter :category_id, :collection => proc { Category.all }, :as => :select
The answer to this can be found here providing you can write your has many though in sql! 这里的答案可以在这里找到,前提是你可以在sql中编写你的有很多!
How to add custom filter to Active Admin? 如何向Active Admin添加自定义过滤器?
I was also searching for same and found working solution as below. 我也在寻找相同的工作解决方案,如下所示。 Posting here so it may help others in future. 在这里发布,以便将来可以帮助其他人。
app/admin/location.rb 应用程序/管理/ location.rb
ActiveAdmin.register Location do
filter :filter_by_category, label: 'Category', as: :select, collection: Category.pluck(:name, :id)
app/model/location.rb 应用程序/模型/ 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
Hope it helps..!! 希望能帮助到你..!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.