我有模特:
class UserWeight < ActiveRecord::Base
self.table_name = 'Weight'
scope :logged_between, lambda { |start_date, end_date|
where(weight_date: start_date.to_date...(end_date.to_date.end_of_day)) unless
start_date.nil? || end_date.nil?
}
# returns the sum of points
def total_points
self.class.Userweight
(UserWeight.blank?) ? 0 : UserWeight.inject(0) {|a, e| a + e.points}
end
end
控制器:
@weights = weight_usages.logged_between(params[:start_date], end_date)
我得到以下权重数据:
weights: [
{
weight: "170.0",
weight_date: "2016-12-28",
points: 1
},
{
weight: "185.0",
weight_date: "2017-01-04",
points: 1
}
.......
]
活动记录正在返回数组的集合。我想访问类方法并在实例方法中执行求和。基于我想要从实例方法返回总分2的数据。知道我该怎么办?
由于
答案 0 :(得分:1)
该方法看起来几乎没有任何意义,因为total_points
是一个实例方法,那么为什么要在中显示所有记录points
的总和实例方法?
除上述注释外,请使用ActiveRecord的方法。您正在寻找sum
:
UserWeight.sum(:points)
方法:
self.class.sum(:points)