【问题标题】:Filter and sum Model with Polymorphic Associations具有多态关联的过滤和求和模型
【发布时间】:2015-08-19 08:28:19
【问题描述】:

我有 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

我怎样才能完成任务?

【问题讨论】:

  • 您要在哪个模型中添加此范围?
  • 我添加范围的模型是捐赠

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


【解决方案1】:

您必须将所有 PersonOrganization 外连接到匹配的 Donation(通过限制 donatable_type)。

然后选择所有连接的 brach_id 列匹配的所有Donations

外部连接必须通过 .joins('..') 指定为搅拌

【讨论】:

    【解决方案2】:
    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})
    }
    

    【讨论】:

    • 我认为它不会起作用,因为人和组织是通过多态关联可捐赠的,而不是捐赠相关联的:/ 这是错误:输出错误:#<:statementinvalid: pg: :undefinedtable: from>
    • 我的错...我只是在编辑我的答案...我想你可以通过 @axel Tetzlaff 的答案去
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 2020-05-14
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多