在Rails应用程序中,我有两个通过has_many
和belongs_to
关联相关的模型:
class Entity < ActiveRecord::Base
has_many :applicants
end
class Applicant < ActiveRecord::Base
belongs_to :entity
end
我正在使用SearchKick首先选择一些实体 - 这个细节并不重要,但 给定现有的Entity对象集合,如何检索所有相关的Applicant对象< / EM>
# 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
答案 0 :(得分:0)
喜欢这个吗?
Applicant.joins(:entity).where("entities.id < ?", 1000)
答案 1 :(得分:0)
Entity.where("id < ? ", 1000).includes(:applicants)
获取所有申请人
Entity.where("id < ? ", 1000).includes(:applicants).collect(&:applicants).flatten
答案 2 :(得分:0)
这个答案来自SearchKick开发人员Andrew Kane:
一种方法是使用
include
选项来预先加载关联。Entity.search "*", include: [:applicants]
另一种选择是从实体获取所有ID,并将它们传递给 对申请人的查询。
Applicant.where(entity_id: entities.map(&:id))
我发现第二个选项对我有用。