user252106
user252106

Reputation:

rails 3 arel eager load not working as expected

class User
  has_many :subscriptions
  ...
end

class Subscription
  belongs_to :user
  ...
end

when i do a User.includes(:subscriptions), the log says:

User Load (0.3ms) SELECT users.* FROM users Subscription Load (0.2ms) SELECT subscriptions.* FROM subscriptions WHERE (subscriptions.user_id IN (1,2,3,5))

i would have expected a single join query, but i don't see it.

does anyone have an explanation for this behavior?

Upvotes: 0

Views: 1843

Answers (1)

johnmcaliley
johnmcaliley

Reputation: 11055

This is the expected behavior, since it can be more efficient than a join in certain situations. As of Rails 2.1, it was changed to execute at least 2 queries. Read this as it relates to :include (now includes in Rails 3):

http://akitaonrails.com/2008/05/25/rolling-with-rails-2-1-the-first-full-tutorial-part-2

And more info in the rails guides:

http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations

You may want to use joins instead, depending on the scenario.

Upvotes: 4

Related Questions