【问题标题】:Rails 3: Scope on an optional has_one associationRails 3:可选 has_one 关联的范围
【发布时间】:2011-07-22 13:57:55
【问题描述】:

我有两种模式:销售和付款

class Sale < ActiveRecord::Base
  has_one :payment
end

class SaleCancelation < ActiveRecord::Base
  belongs_to :payment
end

我想创建两个范围,“有付款”和“没有付款”。

“with_payment”很容易工作:

class Sale < ActiveRecord::Base
  scope :with_payment, joins( :payment )
end

但我如何创建一个范围来查找具有关联付款的每笔销售?

【问题讨论】:

  • (无法回答自己的问题 8 小时,所以解决方案在这里)。刚刚找到了解决方案,使用 MetaWhere Gem(详细说明:metautonomo.us/2010/11/02/metawhere-is-about-to-get-func-yscope :without_payment, joins(:payment.outer).where(:payment =&gt; {:id =&gt; nil})(注意 :payment.outer,它创建了一个外连接而不是一个内连接,这使得所有这种情况下的区别。)

标签: ruby-on-rails ruby-on-rails-3 scope arel


【解决方案1】:

怎么样:

scope :without_payment, where( 'id not in (select sales_id from payments)' )

【讨论】:

  • 找到了另一种方法,仍在决定我将保留哪一个 :D,谢谢!
【解决方案2】:

另一种方法:

scope :without_profile, lambda { includes(:user_profile).where('user_profiles.id is null') }

【讨论】:

  • 我更喜欢这个解决方案,因为连接会比子查询快。
猜你喜欢
  • 2014-01-10
  • 1970-01-01
  • 2015-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多