Search code examples
sqlruby-on-railsrails-admin

Rails Admin - Perform a search into an has_many associated model not loading table


I am implementing Rails Admin for a client and I have two models Job and Candidacy. A Job has many candidacies.From Rails Admin Job Panel, I would like to do a date filter to search between two dates if there is any candidacies.

Here is the code :

# app/models/job.rb
class Job < ApplicationRecord
 has_many :candidacies

end
# app/models/candidacy.rb
class Candidacy < ApplicationRecord
 belongs_to :job

end
# config/initializers/rails_admin.rb

RailsAdmin.config do |config|

 config.model 'Job' do
  list do
   field :candidacies, :date do
    searchable [{Candidacy => :created_at}]
   end
  end
 end
end

When I click on Candidacies Filter and filter between two dates. It raises an error

ActiveRecord::StatementInvalid in RailsAdmin::Main#index
PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "candidacies"

I have all the detail about the SQL query and it is not loading the candidacies table.

SELECT "jobs".* FROM "jobs" WHERE candidacies.created_at BETWEEN '2019-12-11 00:00:00' AND '2019-12-14 23:59:59'

Any idea how to config rails admin to load the table candidacies ?

Thanks !!!

1st Edit :

It works when a add a default_scope to my model Job. But I don't know if it is the proper way to do it.

# app/models/job.rb
class Job < ApplicationRecord
 has_many :candidacies
 default_scope { eager_load(:candidacies) }
end

Solution

  • To avoid eager loading the other table in all future Job queries i suggest you keep the scope only on the job list config.

    # config/initializers/rails_admin.rb
    RailsAdmin.config do |config|
     config.model 'Job' do
      list do
       field :candidacies, :date do
        searchable [{Candidacy => :created_at}]
       end
    
       scopes [:with_candidacies]
      end
     end
    end
    

    And the model

    # app/models/job.rb
    class Job < ApplicationRecord
     has_many :candidacies
     scope :with_candidacies, -> { eager_load(:candidacies) }
    end
    

    Rails admin will auto apply the first scope.