我正在尝试简单地允许在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,但没有任何方法可行。
有没有人经历过这个 - 有人有解决方案吗?
答案 0 :(得分:1)
在某些时候has_many / through比habtm更灵活(你可以有其他字段等)
答案 1 :(得分:0)
你为什么不使用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
答案 2 :(得分:0)
这里的答案可以在这里找到,前提是你可以在sql中编写你的很多内容!
答案 3 :(得分:0)
我也在寻找相同的东西,发现如下工作解决方案。在此处发布信息,以便将来对其他人有帮助。
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
希望它会有所帮助.. !!