5

I'm trying to simply allow filtering of categories on the Locations page for 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.

Has anyone experienced this –– anyone have a solution?

Brian Weinreich
  • 7,692
  • 8
  • 35
  • 59

4 Answers4

4

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

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

Hope it helps..!!

Gagan Gami
  • 10,121
  • 1
  • 29
  • 55
1

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

Jon Soong
  • 117
  • 5
0

The answer to this can be found here providing you can write your has many though in sql!

How to add custom filter to Active Admin?

Community
  • 1
  • 1
hatenine
  • 506
  • 3
  • 13
-1

why aren't you using 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