轨道4总和模型法 [英] Rails 4 Sum by Model Method
问题描述
在我的应用程序,我有一个用户
模式,使用 goal_ytd
方法,它执行一些计算。
In my app, I have a User
model, with a goal_ytd
method, which performs some calculations.
在一个控制器,我有一个变量 @users
这也许是用户
或的ActiveRecord ::关联
用户
,我想总结所有的 @users
的 goal_ytd
秒。
In a controller, I have a variable @users
that might be User
or an ActiveRecord::Relation
of users
, and I would like to sum all of the @users
's goal_ytd
s.
我的第一个倾向是:
@ users.sum(安培;:goal_ytd)
@users.sum(&:goal_ytd)
这扔去precation警告在这两种情况下,因为使用之
上的的ActiveRecord ::关联
要走了对Rails 4.1。
Which threw a deprecation warning in both cases because using sum
on an ActiveRecord::Relation
is going away in Rails 4.1.
于是,我改变了code到:
So, I changed the code to:
@ users.to_a.sum(安培;:goal_ytd)
然后扔了 NoMethodError
,因为在某些情况下, @users
是<$ C $分配C> @users =用户和用户
没有 to_a
方法。
Which then threw a NoMethodError
because, in a certain circumstance, @users
is assigned by @users = User
and User
has no to_a
method.
指定 @users
使用 @users = User.all
则抛出去precation警告,因为关联#所有
也去precated。
Assigning @users
using @users = User.all
throws a deprecation warning because Relation#all
is also deprecated.
有没有办法让所有的用户
作为一个数组?有没有更好的办法?
Is there a way to get all Users
as an array? Is there a better way?
推荐答案
在Rails的4.1
On Rails 4.1
如果 goal_ydt
是用户表中的列:
@users.sum(:goal_ydt)
如果 goal_ydt
是一个方法用户
类:
@users.to_a.sum(&:goal_ydt)
这篇关于轨道4总和模型法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!