简体   繁体   English

轨道总和活动记录关联关系

[英]rails sum Active Record Association Relation by

I have Foo::ActiveRecord_AssociationRelation and I when I run this code in the console on that relation: 我有Foo::ActiveRecord_AssociationRelation ,当我在该关系上的控制台中运行此代码时,我得到了:

.inject(0){|sum,x| x.dimension == dimension && x.dimension_value == dimension_value && x.metric == metric ? (sum += x.metric_value) : ()}

I get the expected summed value it should return. 我得到了它应该返回的预期总和值。

However when I added this code to the model 但是,当我将此代码添加到模型中时

def self.sum_by(dimension, dimension_value, metric)
...
end

I get this error: 我收到此错误:

NoMethodError: undefined method `inject' for #<Class:0x000000094cbbd0>

How do I apply that code correctly? 如何正确应用该代码? Given that Foo inherits from ActiveRecord::Base I thought it should work. 鉴于Foo继承自ActiveRecord::Base我认为它应该可以工作。

I'm assuming that you are removing the leading period when you copy it into a class. 我假设您在将前置时间段复制到课程中时正在删除前置时间段。

However, inject is not a method on an ActiveRecord::Base object. 但是,注入不是ActiveRecord :: Base对象上的方法。 It is from the Enumerable module, so you'd need to call it on something that has the enumerable module mixed in. 它来自Enumerable模块,因此您需要在混有可枚举模块的东西上调用它。

For instance, if you were trying to sum every instance of Foo, you could call Foo.all first, returning an array of all objects. 例如,如果您尝试对Foo的每个实例求和,则可以首先调用Foo.all,返回所有对象的数组。 so your code would look as follows. 因此您的代码如下所示。

def self.sum_by(dimension, dimension_value, metric)
  Foo.all.inject(0){|sum, a_foo| foo.dimension == dimension && foo.dimension_value == dimension_value && foo.metric == metric ? (sum += foo.metric_value) : ()}
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM