When an association has joins (either to filter the association or calculate something), it cannot be eager loaded with includes. The joins command seems to be omitted and I get an error saying the table doesn’t exist cause it didn’t the join when eager loading.
Example:
class User < ActiveRecord::Base
has_many :
purchases
# Perform joins and attach some calculations to the User object
scope :add_stats, -> { group("users.id").joins(:purchases).select("users.*, SUM(purchases.price) AS total_purchases") }
end
class Purchase < ActiveRecord::Base
belongs_to :user
end
The add_stats
scope represents heavy calculations attached to the User
objects. So if I want to get all User
objects with stats, I just write User.all.add_stats
.
So far so good. Now I want to fetch some Purchase
objects and eager load the User
s with stats as well. I’ve tried this:
belongs_to :user, -> { add_stats }
But then when Rails eager load the users, it seems to remove.group("user.id").joins(:purchases)
and complain on purchases.price
- “purchases table unknown”. So the .select()
is the only thing preserved from the scope.
How do I apply a scope (with working .group().joins()
) to the eager load query of all included belongs_to :user
objects?