【发布时间】:2012-02-28 04:35:31
【问题描述】:
我有一个 has_many :through 像这样设置的关系
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
所以,一个Situation有很多Notifications,可以有很多类型(Notiftype)。
我的问题是尝试查询尚未为特定situation 设置的notiftypes。
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。
【问题讨论】:
标签: ruby-on-rails activerecord has-many-through