如何从 Rails 中的现有选择集中检索所有相关对象

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

在 Rails 应用程序中,我有两个模型,它们通过 has_manybelongs_to 关联关联:

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

我首先使用 SearchKick select 一些实体 - 这方面的细节并不重要,但是 给定一个现有的实体对象集合,如何我可以检索所有相关的 Applicant 对象吗?

# 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.???

这可行,但由于 selection 很大,速度非常慢:

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

是否有 Rails 检索与 selected 实体相关的申请人的简写?

我尝试过的其他事情:

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

像这样?

Applicant.joins(:entity).where("entities.id < ?", 1000)
Entity.where("id < ? ", 1000).includes(:applicants)

获取所有申请人

Entity.where("id < ? ", 1000).includes(:applicants).collect(&:applicants).flatten

此回答来自 SearchKick 的开发者 Andrew Kane:

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))

我发现第二种选择很适合我。