Reputation:
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
.* FROMusers
Subscription Load (0.2ms) SELECTsubscriptions
.* FROMsubscriptions
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
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