Search code examples
ruby-on-railsactiverecordassociationssearchkick

How to retrieve all related objects from an existing selection set in Rails


In a Rails app I have two models which are related via has_many and belongs_to associations:

class Entity < ActiveRecord::Base
  has_many :applicants
end
class Applicant < ActiveRecord::Base
  belongs_to :entity
end

I'm using SearchKick to first select some Entities - the details of this don't really matter, but given an existing collection of Entity objects, how can I retrieve all of the related Applicant objects?

# select some entities (in my app I'm using SearchKick to run the search)
entities = Entity.search params[:query]

# now find the applicants related to the selected entities
applicants = entities.???

This works, but is very slow given a large selection:

# retrieve the applicants related to the selected entities
applicants = []
entities.each do |entity|
  applicants += entity.applicants
end

Is there a Rails short-hand to retrieve the Applicants related to the selected Entities?

Other things I've tried:

entities.class => Entity::ActiveRecord_Relation 
entities.applicants => #error
entities.applicant_ids => #error

Solution

  • This answer came from Andrew Kane, the developer of SearchKick:

    One way is to use the include option to eager load associations.

    Entity.search "*", include: [:applicants]
    

    Another option is to get all ids from the entities, and pass them into a query for applicants.

    Applicant.where(entity_id: entities.map(&:id))
    

    I found that the second option worked well for me.