ActiveRecord::EagerLoadPolymorphicError: Can not eagerly load the polymorphic association

家住魔仙堡 提交于 2019-11-30 18:16:16
Pan Thomakos

There are two issues here:

  1. Summing over a polymorphic association.
  2. Condition over a polymorphic association.

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

  1. Transactions.count(:all, :joins => :account)
  2. Transactions.find(:all, :conditions => "accounts.status = 'active'", :joins => :account)

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
)

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

Additional to pan's answer, you could even do a union instead of adding them. which executes only one query

For those that got this error even when they aren't trying to query conditions on the polymorphic association, it's because includes decided to call eager_load when polymorphic associations are only supported by preload. It's in the documentation here: http://api.rubyonrails.org/v5.1/classes/ActiveRecord/EagerLoadPolymorphicError.html

So you should always use preload for polymorphic associations.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!