我有一个has-many People的Project模型。
给定一个包含大量Projects的ActiveRecordRelation,如何有效地获取一个包含与所有项目关联的所有唯一People的ActiveRecordRelation?
基本上,我在寻找一种有效的方法:
@people = @projects.flat_map {|project| project.people}.uniq发布于 2013-12-15 00:45:56
急切加载似乎不能在has_many中正常工作,或者至少不够聪明。Rails将立即加载关联,但当您在特定实例上调用该关系时,会求助于查询。
示例(非实际查询):
@articles = Article.includes(:comments)
#> Article Load: SELECT * from articles
#> Comment Load: SELECT * from comments where article_id IN(1,2,3,4)
@articles.first.comments
#> Comment Load: SELECT * from comments where article_id IN(1)在@articles.first.comments中,我希望看到Comment Load (Cache)或类似的内容,因为该注释已经加载。
可能有一个更好的替代方案,但我会简单地执行一个自定义查询,例如:
@people = People.where("project_id IN(?)", @projects.map(&:id))
Rails 4:
@people = People.where(project_id: @projects.map(&:id))
https://stackoverflow.com/questions/20584945
复制相似问题