Rails / Ruby:对ActiveRecord_AssociationRelation执行计算(包括自定义foreign_key)

时间:2014-09-30 03:33:23

标签: ruby-on-rails foreign-keys rails-activerecord

我希望我在标题中提出正确的问题,因为我的问题感觉它应该是非常微不足道的,但我很难搞清楚。

我有两个基本的models标准has_manybelongs_to关系:

class StandingEvent < Event
  belongs_to :standing, foreign_key: 'actor_id'
end

class Standing < ActiveRecord::Base
  has_many :standing_events
end

我的目标很简单:计算通过 StandingEvents关联获取的Standing记录集合中字段的总和。 As预计,此集合为type StandingEvent::ActiveRecord_AssociationRelation

忽略其他所有内容并将其剪切到最小的骨头,运行以下内容时出错:

@standing = Standing.find(4)
@standing.standing_events.sum(:change)

产生的错误如下:

Mysql2::Error: Unknown column 'events.standing_id' in 'where clause': SELECT SUM(`events`.`change`) AS sum_id FROM `events` WHERE `events`.`actor_type` IN ('StandingEvent') AND `events`.`standing_id` = 4

因此,从上面的错误可以看出,完全问题是生成的SQL查询试图使用standing_id作为列名(可能是因为相关记录)而不是模型本身(actor_id)中指定的实际列名称。

此问题仅在使用calculate方法(例如sum)时出现,因为我在整个应用程序中使用这两种模型及其关联非常严重。< / p>

唯一的方式&#34;周围&#34;到目前为止我发现的这个问题看起来很糟糕(并且让我感到不必要),这本质上是将我的where子句和sum链接到基类,而不是之前使用的收集了一组相关记录:

@standing = Standing.find(4)
StandingEvent.where(standing: @standing).sum(:change)

上面的代码执行计算没有问题,但由于我想在单个请求中对同一个集合执行多次计算,所以每次重新查询整个集合似乎是一个非常糟糕的解决方案上面(虽然我可能不太了解Rails,但公平)。

正如我的问题标题中所提到的,我无法帮助但想知道这是否是某种与使用我指定的foreign_key字段相关的错误(缺少更好的术语) child关联(在这种情况下,foreign_key StandingEvent Standing关联的actor_id重命名为{{1}}。

非常感谢任何和所有见解!

1 个答案:

答案 0 :(得分:0)

我认为您需要在关联的两边指定foreign_key

has_many :standing_events, foreign_key: :actor_id