Reputation: 43401
I have a Project
model that has-many
People
.
Given an ActiveRecordRelation
containing a large number of Projects
, how can I efficiently get an ActiveRecordRelation
containing all unique People
associated with all the projects?
Basically I'm looking for an efficient way of doing:
@people = @projects.flat_map {|project| project.people}.uniq
Upvotes: 0
Views: 59
Reputation:
Eager loading does not appear to work correctly with has_many
, or is not clever enough, at least. Rails will eager load the association, but then resort to a query when you call that relation on a specific instance.
Example (not actual queries):
@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)
In the @articles.first.comments
, I would expect to see Comment Load (Cache)
or something similar, as that comment has already been loaded.
There might be a better alternative, but I would simply perform a custom query such as:
@people = People.where("project_id IN(?)", @projects.map(&:id))
Rails 4:
@people = People.where(project_id: @projects.map(&:id))
Upvotes: 1