ruby-on-railsactiverecordrails-activerecord

How do I eager load multiple associations in same query with ActiveRecord?


Given the following:

How do I in one query get all the model titles inside any one Project without using map or something similar AND without getting the N + 1 problem?

By using map, I have various solutions that work, but they all query the database more than once:

Project.joins(collectors: { gs_collector: :model }).find(92666).collectors.map{ |coll| coll.gs_collector.model.title }

Solution

  • You can do something like this

    Model.joins(gs_collector: :collector).where(collectors: { project_id: 92666 }).pluck(:title)