You probably could have said:
def total_points
self.referrals.to_a.sum(&:point_value)
end
And then #sum is from Enumerable (as extended by ActiveSupport) rather
than ActiveRecord::Calculations::ClassMethods (note the use of .to_a
in there to get a real array rather than an association proxy)
-Rob
On Jan 2, 2009, at 4:07 PM, Taylor Strait wrote:
>
> Fixed. The short version of the story is that rails' .sum helper hits
> the DB N+1 times. Writing a custom sum method solves this problem.
> In
> my case, the top method only hits the DB twice whereas the second
> method
> hits the DB N+2 times.
>
> # 2 queries
> def total_points
> sum = 0
> self.referrals.each {|ref| sum += ref.point_value}
> sum
> end
>
> # N+2 queries
> def total_points
> self.referrals.sum :point_value
> end
>
> So :include DOES work as long as you are careful to manipulate the
> collection in ruby and not use another ActiveRecord method to do
> summation.
> --
> Posted via http://www.ruby-forum.com/.
>
> >
Rob Biedenharn http://agileconsultingllc.com
[email protected]
+1 513-295-4739
Skype: rob.biedenharn
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---