ActiveRecord的:: EagerLoadPolymorphicError:不能急于加载多态性关联 [英] ActiveRecord::EagerLoadPolymorphicError: Can not eagerly load the polymorphic association

查看:163
本文介绍了ActiveRecord的:: EagerLoadPolymorphicError:不能急于加载多态性关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Transaction < ActiveRecord::Base
  belongs_to :account, :polymorphic => true
end

class Bankaccount < ActiveRecord::Base
  has_many :transactions, :as => :account
end

class Creditcard < ActiveRecord::Base
  has_many :transactions, :as => :account
end

争取做交易的总和,其中帐户被激活。

Trying to do a summation of transactions where the account is active.

Transaction.sum(:all, :conditions => "account.status = 'active'", :include => :account)

所以一些阅读后,我看到了这一点: 其原因是父模型的类型是一个列值,因此其对应的表名称不能放在FROM / JOIN该查询的条款。 表名是bankaccounts和creditcards这是否意味着他们应该是单数? 另外,ACCOUNT_TYPE是一个字符串或者的BankAccount或信用卡式反映模型,但它应该是在表名呢?

So after some reading I came across this: The reason is that the parent model‘s type is a column value so its corresponding table name cannot be put in the FROM/JOIN clauses of that query. The table name is bankaccounts and creditcards so does that mean they should be singular? Also the account_type is a string either Bankaccount or Creditcard to reflect the model but should it be the tablename instead?

推荐答案

有两个问题:

  1. 总结过的多态关联。
  2. 在条件上的多态关联。

您不能真正做到无论这些事情。所以,你应该通过执行这两个查询得到同样的错误:

You can't actually do either of these things. So you should get the same error by performing these two queries:

  1. Transactions.count(:所有,:加入=>:帐户)
  2. Transactions.find(:所有,:条件=>accounts.status ='主动':加入=>:帐户)

要真正得到你需要的,你必须明确列出了可能的父多态关联的信息。这样做的一个方法是简单地使用SQL和左连接,这样就可以使用一个单一的查询。使用Rails这可以通过两个查询来执行:

To actually get the information you need you must explicitly list out the possible parent polymorphic associations. One way to do this is to simply use SQL and LEFT JOINS, so that you can use a single query. Using Rails this can be performed with two queries:

Creditcard.sum(
  :all, 
  :select => "transactions.amount", 
  :conditions => "creditcards.status = 'active'", 
  :joins => :transaction
) + Bankaccount.sum(
  :all, 
  :select => "transactions.amount", 
  :conditions => "bankaccounts.status = 'active'", 
  :joins => :transaction
)

PS:这是最好的使用方法:加入代替:包括,如果你不上查询后访问的加盟对象计划

P.S: It's best to use :join instead of :include if you don't plan on accessing the joined objects after the query.

这篇关于ActiveRecord的:: EagerLoadPolymorphicError:不能急于加载多态性关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆