Searchkick: How to retrieve all related records from a SearchKick::Results object?

Created on 12 Jul 2016  路  1Comment  路  Source: ankane/searchkick

I have two models which are related via has_many and belongs_to associations. One of the models is indexed via SearchKick:

class Entity < ActiveRecord::Base
  has_many :applicants
  searchkick locations: ["location"]
  def search_data
    attributes.merge location: {lat: latitude, lon: longitude}
  end
end

class Applicant < ActiveRecord::Base
   belongs_to :entity
end

I'm using SearchKick to select Entities. My search is based on a spatial query, but it shouldn't really matter - the end result is a SearchKick::Results object:

whereClause = {location: {top_left: {lat: params[:ymax], lon: params[:xmin]}, bottom_right: {lat: params[:ymin], lon: params[:xmax]}}}
entities = Entity.search "*", where: whereClause
entities.class => Searchkick::Results

How can I find all the matching Applicants? This works, but is very slow given a large selection:

applicants = []
entities.each do |entity|
  applicants += entity.applicants
end

Thanks

Most helpful comment

Hey Stephen, 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))

>All comments

Hey Stephen, 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))
Was this page helpful?
0 / 5 - 0 ratings

Related issues

gerrywastaken picture gerrywastaken  路  3Comments

jnimety picture jnimety  路  4Comments

matthewmoss picture matthewmoss  路  4Comments

rajatgarg79 picture rajatgarg79  路  4Comments

yurgon picture yurgon  路  4Comments