Reputation: 3594
Let's say I have two models: User and Point.
Point belongs_to the user. Point has an 'amount'. I want to define a method in the Point model that will return the user's total points. I'd like to call it in such a manner: user.points.total
I just don't know how to define the method in the Point model in such a way that I don't have to pass it the User's ID. I'd imagine there is a simple way to do this, but my Googlefu is failing me.
Upvotes: 0
Views: 421
Reputation: 5111
Assuming that User model has
has_many :points
you can do like this in User model
def total_points
points.sum(:amount)
end
Upvotes: 3
Reputation: 13054
Consider using #sum, which uses SQL sum to do an aggregation.
For example,
person.points.sum('amount')
or
# inside User.rb
def total
points.sum('amount')
end
Upvotes: 0
Reputation: 29389
Given that you want the method defined in the Point
model, you'd want to use:
class Point
def total
user.points.sum(:amount)
end
end
You can then get the total points for the user associated with a given point
by invoking point.total
. You can't get total points through User.points.total
because User
is a class and doesn't refer to a particular user.
Upvotes: 0