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 endThe 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 Users 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?
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/41e837d1-0838-4d54-a535-265763b0a926%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
No comments:
Post a Comment