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



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

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

我正在使用 SearchKick 首先选择一些实体 - 这并不重要,但给定实体对象的现有集合,如何检索所有相关的申请人对象

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

这有效,但考虑到大量选择,速度非常慢:

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

是否有一个 Rails 速记来检索与所选实体相关的申请人?

我尝试过的其他事情:

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

像这样?

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

这个答案来自SearchKick的开发者Andrew Kane:

一种方法是使用 include 选项来预先进行负载关联。

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

另一种选择是从实体获取所有 ID,并将它们传递给 对申请人的查询。

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

我发现第二个选项对我来说效果很好。

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

获取所有申请人

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

最新更新