使用多态关联过滤和求和模型

时间:2015-08-19 08:28:20

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

我有3个模特 - 捐款,人员,组织

class Donation < ActiveRecord::Base
   belongs_to :donatable, polymorphic: true
end

class Person < ActiveRecord::Base
   belongs_to :branch
   has_many :donations, as: :donatable
end

class Organization < ActiveRecord::Base
   belongs_to :branch
   has_many :donations, as: :donatable
end

捐款可以来自个人或组织。人和组织属于分支机构。

我正在尝试过滤来自特定分支的捐款并将它们总计,这是我写的范围:

scope :for_branch, lambda { |branch_id| 
    return nil  if branch_id.blank?
    joins(:donatable).where(:branch_id => branch_id)
}

它返回错误:

Cannot eagerly load the polymorphic association :donatable

我该如何完成任务?

2 个答案:

答案 0 :(得分:1)

您必须将所有A<>Person外部加入匹配的Organization(通过限制donatable_type)。

然后选择所有联接的brach_id列匹配的所有Donation

外部联接必须指定为Donations

的搅拌

答案 1 :(得分:0)

Donation.joins("left join persons on persons.donatable_id = donations.id").joins("left join organizations on organizations.donatable_id = donations.id").where('persons.branch_id=? OR organizations.branch_id=?', branch_id, branch_id)

如果您需要范围

scope :by_branch, lambda { |branch_id|
   return nil  if branch_id.blank?
   joins: ["left join persons on persons.donatable_id = donations.id",
           "left join organizations on organizations.donatable_id = donations.id"],
   conditions: %('persons.branch_id=#{branch_id} OR organizations.branch_id=#{branch_id})
}