Search code examples
rails-admin

rails_admin gem filter with has_many_through association


In my application

Product has many categories through category_has_products

Category has many products through category_has_products

Initially, I used

at product.rb

default_scope { includes(:brand, :categories) }

and in rails_admin config set it as

field :categories, :string do
 searchable [{Category => :name}]
end  

This works like a charm. This got into performance issues due to has_many_through(other pages using product details got affected)

So I removed the default_scope from product.

After that, I am getting

PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "categories"

any idea on how to preload categories?

Note: rails_admin gem version is 0.8.1 only. I am not able to update to latest version 1.X.X


Solution

  • I found answer

    in product.rb

    scope :include_categories, -> {includes(:categories)}
    class << self
      alias_method :all_products, :include_categories
    end  
    

    admin_product_config.rb

    from
        scopes %i[all brandless unmatched matched ignored fresh diy_only]
    to
        scopes %i[all_products brandless unmatched matched ignored fresh diy_only]
    

    To add filter option

      field :categories, :string do
        searchable [{Category => :name}]
      end      
      configure :categories do
        hide
      end 
    

    Thank you @jxpx777 https://github.com/sferik/rails_admin/issues/1348#issuecomment-39373394