Given the following:
- Project
has_manycollectors - Collector
has_onegs_collector - GsCollector
has_onemodel - Model has a field named
title
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 }
joinsis used for.joinsis not actually used to eager load records and solve the common n+1 problem. It's used to add a INNER JOIN clause that can be used to filter out rows with no match in the join table or to add conditions based on the join table. No columns in the joined table will be selected. For eager loading you eager_load, preload or includes. bigbinary.com/blog/preload-vs-eager-load-vs-joins-vs-includes