Let's say I have two models: User and Point.
假设我有两个模型:User和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
Point belongs_to用户。 Point有一个'金额'。我想在Point模型中定义一个返回用户总分的方法。我想以这样的方式调用它: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.
我只是不知道如何在Point模型中定义方法,以便我不必将其传递给用户的ID。我想有一个简单的方法可以做到这一点,但我的Googlefu让我失望了。
3 个解决方案
#1
3
Assuming that User model has
假设用户模型有
has_many :points
you can do like this in User model
你可以在用户模型中这样做
def total_points
points.sum(:amount)
end
#2
0
Given that you want the method defined in the Point
model, you'd want to use:
鉴于您需要Point模型中定义的方法,您需要使用:
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.
然后,您可以通过调用point.total来获取与给定点关联的用户的总分数。您无法通过User.points.total获得总分,因为User是一个类,并且不引用特定用户。
#3
0
Consider using #sum, which uses SQL sum to do an aggregation.
考虑使用#sum,它使用SQL sum进行聚合。
For example,
例如,
person.points.sum('amount')
or
要么
# inside User.rb
def total
points.sum('amount')
end
#1
3
Assuming that User model has
假设用户模型有
has_many :points
you can do like this in User model
你可以在用户模型中这样做
def total_points
points.sum(:amount)
end
#2
0
Given that you want the method defined in the Point
model, you'd want to use:
鉴于您需要Point模型中定义的方法,您需要使用:
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.
然后,您可以通过调用point.total来获取与给定点关联的用户的总分数。您无法通过User.points.total获得总分,因为User是一个类,并且不引用特定用户。
#3
0
Consider using #sum, which uses SQL sum to do an aggregation.
考虑使用#sum,它使用SQL sum进行聚合。
For example,
例如,
person.points.sum('amount')
or
要么
# inside User.rb
def total
points.sum('amount')
end