簡體   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