2011-07-22 92 views
4

范围,我有两个模式:销售和支付的Rails 3:可选HAS_ONE协会

class Sale < ActiveRecord::Base 
    has_one :payment 
end 

class SaleCancelation < ActiveRecord::Base 
    belongs_to :payment 
end 

我要创建两个范围,“付款”和“不付款”。

“with_payment”作品easyly:

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

但我怎么可以创建一个发现每销售,做具有关联的付款示波器?

+0

(不能回答自己的问题,8小时,这样的解决方案放在这里)。 刚刚发现的解决方案,使用MetaWhere宝石(详细explenation在这里:http://metautonomo.us/2010/11/02/metawhere-is-about-to-get-func-y/ 'scope:without_payment ,加入(:payment.outer).where(:payment => {:id => nil})' (请注意**:payment.outer **,它创建一个外连接而不是内连接, ) – Majiy

回答

4

如何:

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

正是我在找的!谢谢! – yorch

+0

找到了另一种方式,仍然决定我要保留哪一个:D,谢谢! – yorch

4

另一种方式来做到这一点:

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

我更喜欢这个解决方案,因为连接速度会比子查询 – dgmdan

0
class Sale < ActiveRecord::Base 
    scope :with_payment, joins(:payment) 
    scope :without_payment, Sale.all - Sale.with_payment 
end 
+0

你完全错过了范围的想法...范围应该返回关联无论如何,当你在实际生产应用中尝试它时,这段代码将会终止你的服务器。 –