2012-02-28 44 views
1

我有一个的has_many:通过关系建立像这样Rails的活动记录查询:查询记录上的has_many的一面:通过未使用与另一侧的特定记录

class Situation < ActiveRecord::Base 
    has_many :notifications 
    has_many :notiftypes, through: :notifications 
end 

class Notification < ActiveRecord::Base 
    belongs_to :situation 
    belongs_to :notiftype 
end 

class Notiftype < ActiveRecord::Base 
    has_many :notifications 
    has_many :situations, through: :notifications 
end 

所以,情况有很多通知,可以有很多种类型(Notiftype)。

我的问题是试图查询notiftypes尚未设置为特定的situation

Want to find records with no associated records in Rails 3

该问题的答案让我接近,但只发现还没有被设置在所有Notiftypes点。

如果是这样的标准:situation的has_many :notiftypes我可以做左外连接,像这样

myquery = Notiftype.joins('LEFT OUTER JOIN situations ON situations.notiftype_id = notiftype.id').where('notiftype_id IS NULL') 

,但我真的不知道如何与它们之间的中间表做到这一点。

我一直在尝试连续连接,但它不工作。我不知道如何加入两个分开的表格。

任何人都可以解释正确的方式来查询分贝?我现在正在使用SQLite,Rails 3.1,Ruby 1.9.2,但将来可能会使用Postgresql。

回答

0

试试这个:

class Situation < ActiveRecord::Base 
    # ... 
    has_many :notiftypes, through: :notifications do 

    def missing(reload=false) 
     @missing_notiftypes = nil if reload 
     @missing_notiftypes ||= proxy_owner.notiftype_ids.empty? ? 
     Notiftype.all : 
     Notiftype.where("id NOT IN (?)", proxy_owner.notiftype_ids) 
    end 
    end 
end 

我们拿到丢失Notiftype

situation.notiftypes.missing 

如果你想进一步优化这种使用一个SQL,而不是两个,你可以做到以下几点:

class Situation < ActiveRecord::Base 
    # ... 
    has_many :notiftypes, through: :notifications do 

    def missing(reload=false) 
     @missing_notiftypes = nil if reload 
     @missing_notiftypes ||= Notiftype.joins(" 
      LEFT OUTER JOIN (#{proxy_owner.notiftypes.to_sql}) A 
      ON A.id = notiftypes.id"). 
     where("A.id IS NULL") 
    end 
    end 
end 

您可以访问缺少的NotifyType为:

situation.notiftypes.missing 
+0

用一个SQL解决方案更新了答案,看看。 – 2012-02-28 18:24:15

+0

它的工作原理!我用http://stackoverflow.com/questions/7001810/alternative-method-for-proxy-owner-in-activerecord替换了proxy_owner – bknoles 2012-02-28 20:05:30

+0

对不起......我早点击输入。我用proxy_association.owner替换proxy_owner基于此线程 http://stackoverflow.com/questions/7001810/alternative-method-for-proxy-owner-in-activerecord 这是必要的吗?我没有得到proxy_owner方法的任何错误,并且他们都正常工作。 – bknoles 2012-02-28 20:08:03