【发布时间】:2016-11-13 10:16:18
【问题描述】:
在 Rails 应用程序中,我有两个模型,它们通过 has_many 和 belongs_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
【问题讨论】:
标签: ruby-on-rails activerecord associations searchkick