-1

Given the following:

  • Project has_many collectors
  • Collector has_one gs_collector
  • GsCollector has_one model
  • 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 }
1
  • You have misunderstood what joins is used for. joins is 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 Commented Jun 1, 2024 at 8:56

1 Answer 1

1

You can do something like this

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.