Question

Say I have a Post and User model where the User has_many posts. The User model has a name property.

Say I want to display each User#name in a query of Post objects with something like Post.all.each {|post| puts post.user.name}. This works, but Rails issues a Database query for each of the N posts to look up each individual user's name like

SELECT  "users".* FROM "users"  WHERE "users"."id" = ? LIMIT 1  [["id", 25]]

Is there a way to tell Rails it can look this up through a join rather than issuing a separate query for each instance? If I try to use standard joins like Post.all.joins(:user).select('posts.*,users.name'), the ActiveRecord::Relation object comes back appropriately, but during the iteration a new queries is still issued for each Post in the row.

Was it helpful?

Solution

You could try:

Post.includes(:user)

It's called eager loading , performance wise this should only issue two DB queries (check docs here)

Docs recommend using Joins instead when you need to apply conditions on loading (e.g Posts for users with names starting with 's')

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top