Rails预加载多态关联

时间:2016-11-15 19:38:23

标签: ruby-on-rails ruby-on-rails-4 activerecord polymorphic-associations

我有以下模特关系:

class Customer < ActiveRecord::Base
   has_many transactions
end
class Transaction < ActiveRecord::Base
   belongs_to :customer
   belongs_to :ta_type, polymorphic: true
end 

class Downpament < ActiveRecord::Base
   has_one :transaction, as: :ta_type
end 
 class Installemnt < ActiveRecord::Base
   has_one :transaction, as: :ta_type
end 

我可以像这样预加载多态关联:

#app/model/transaction.rb 
def index
  ...
  transactions = self.includes(:ta_type, customer:[:location])
  ...
end

但我需要客户的条件。以下查询也有效。

transactions = self.includes(customer:[:location]).
    where(customer: {office_id: office_id})
然而,这两者的构成不起作用

transactions = self.includes(:ta_type, customer:[:location]).
    where(customer: {office_id: office_id})

打破并抛出

Completed 500 Internal Server Error in 113ms (ActiveRecord: 3.1ms)
ActiveRecord::EagerLoadPolymorphicError (Cannot eagerly load the  polymorphic association :ta_type):

我发现this出色的帖子描述了我遇到的问题。但我无法让它发挥作用。

我尝试使用单独的连接和预加载以及连接,从而导致相同的异常。

 transactions = self.
     preload(:ta_type, customer:[:location]]).
     joins(:ta_type).
     where(customer: {office_id: office_id})

preload_assocications方法似乎是一个好主意,但它已从rails 3.0.9中删除。

如何正确地将多态关联与条件一起预加载?

0 个答案:

没有答案