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
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))
Most helpful comment
Hey Stephen, one way is to use the
includeoption to eager load associations.Another option is to get all ids from the entities, and pass them into a query for applicants.