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。
用一个SQL解决方案更新了答案,看看。 – 2012-02-28 18:24:15
它的工作原理!我用http://stackoverflow.com/questions/7001810/alternative-method-for-proxy-owner-in-activerecord替换了proxy_owner – bknoles 2012-02-28 20:05:30
对不起......我早点击输入。我用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