覆盖ActiveRecord关联条件

时间:2013-12-18 13:57:07

标签: ruby-on-rails activerecord ruby-on-rails-3.2

我在Rails 3.2应用程序的Project模型中有这个关联:

has_many :pledges, conditions: { paid: true }

在一个地方,我需要所有未付的承诺。除了两个明显的解决方案(定义另一个与paid: false条件的关联或找到与Pledge.where...的承诺),是否有可能暂时放弃条件?

类似于:

project.pledges.unscoped.where(paid: false)   # does not work since the link to project is also lost
project.pledges.where(paid: false)            # no good since it does "paid=t AND paid=f"

1 个答案:

答案 0 :(得分:0)

为什么不将范围添加到Pledge模型中?

class Pledge < ActiveRecord::Base
  scope :paid, -> {
    where(paid: true)
  }
  scope :unpaid, -> {
    where(paid: false)
  }
end

然后你可以这样做:

project.pledges.paid
project.pledges.unpaid

您还需要从项目模型中的关联中删除条件。

[EDIT]替代解决方案:

在产品中添加第二个关联以支付未付款的承诺:

class Product
  has_many :unpaid_pledges, class_name: Pledge, conditions: { paid: false }
end

然后你可以做

project.pledges #these are all paid
project.unpaid_pledges #all unpaid pledges belonging to product