I’ve been having this problem that I just can’t wrap my mind around. I need to get a sum the attribute “views” in my object, however, when using :include, I get a very innacurate sum.
>> c = Category.find 181
>> c.pages.sum(:views, :include => [:tags, :author], :conditions => q)
=> 48448
If I remove the :include, I get the correct sum.
>> c.pages.sum(:views, :conditions => q)
=> 11991
The amount of pages is the same in both queries, so I have no idea why that value could be any different. Going through each page will work as well.
>> c.pages.find(:all, :include => [:tags, :author], :conditions => q).each {|p| a += p.views}; a
=> 11991
:tags and :author do not have a :views attribute or even anything remotely similar, and even specifying the attribute with pages.views yields the same result.
Unfortunately, I need to get that value through the database in order to quickly generate a graph for the views. The q variable used in the conditions is the filter, and the reason the :include is needed. I don’t understand what could be causing this or where that 48448 value is coming from;
I’d appreciate any help in this, and thanks in advance.
Assume situation
using
you are duplicating page with id=1 two times:
Sum on column pages.views for this result set is 20 not 10.
[Edited]
Rewritten query witout using :include