rails_admin: has_many :through associations filter problem

Hi ,I have a problem with adding has many through association to filter . When I try to add this code :

list do
    field :model ,:has_many_association do
          searchable :name
     end
end'

and then I add choose filter on the view I give the exception :

Unknown column ‘model.name’ in ‘where clause’: SELECT another_model.* FROM another_model WHERE (((model.name_en LIKE ‘%test%’)))

The same problem I found on the StackOVerflow but it has no answer 😦 http://stackoverflow.com/questions/13529634/rails-admin-searchable-association. Could you help me to resolve it?

About this issue

  • Original URL
  • State: closed
  • Created 12 years ago
  • Comments: 27 (10 by maintainers)

Commits related to this issue

Most upvoted comments

@vergenzt Thanks for your solution, it helped me a lot!!! But it introduced for me an error on all other queries.

NoMethodError (undefined method `page’ for nil:NilClass):

Finally I found that the problem was in the build method of your patch.

def build
  super.includes(*(@includes.uniq)) if @includes.any? 
end

This method returns nil if includes is empty without calling the super method and that fires the no method exception, when pagination is invoked on the result, e.g. in https://github.com/sferik/rails_admin/blob/master/lib/rails_admin/adapters/active_record.rb :36

scope = scope.send(Kaminari.config.page_method_name, options[:page]).per(options[:per])

I think the correct solution should be this

def build
  @includes.any? ? super.includes(*(@includes.uniq)) : super
end

So, the complete working patch is now:

require 'rails_admin/adapters/active_record'

module RailsAdmin::Adapters::ActiveRecord
  module WhereBuilderExtension
    def initialize(scope)
      @includes = []
      super(scope)
    end

    def add(field, value, operator)
      @includes.push(field.name) if field.association?
      super(field, value, operator)
    end

    def build
      @includes.any? ? super.includes(*(@includes.uniq)) : super
    end
  end

  class WhereBuilder
    prepend WhereBuilderExtension
  end
end