Note that there are some explanatory texts on larger screens.

plurals
  1. PORails active record query: Find records on one side of a has_many :through that haven't been used with a particular record on the other side
    text
    copied!<p>I have a has_many :through relationship set up like so</p> <pre><code>class Situation &lt; ActiveRecord::Base has_many :notifications has_many :notiftypes, through: :notifications end class Notification &lt; ActiveRecord::Base belongs_to :situation belongs_to :notiftype end class Notiftype &lt; ActiveRecord::Base has_many :notifications has_many :situations, through: :notifications end </code></pre> <p>So, a Situation has many Notifications, which can be of many types (Notiftype).</p> <p>My problem is trying to query for the <code>notiftypes</code> that have not been set for a particular <code>situation</code>.</p> <p><a href="https://stackoverflow.com/questions/5319400/want-to-find-records-with-no-associated-records-in-rails-3">Want to find records with no associated records in Rails 3</a></p> <p>The answers in that question get me close, but only to the point of finding Notiftypes that have not been set AT ALL.</p> <p>If this were the standard <code>:situation</code> has_many <code>:notiftypes</code> I could just do a Left Outer Join like so</p> <pre><code>myquery = Notiftype.joins('LEFT OUTER JOIN situations ON situations.notiftype_id = notiftype.id').where('notiftype_id IS NULL') </code></pre> <p>but I'm really not sure how to do this with the intermediate table between them. </p> <p>I have been trying consecutive joins but it's not working. I'm not sure how to join the two separated tables.</p> <p>Can anyone explain the right way to query the db? I am using SQLite, Rails 3.1, Ruby 1.9.2 right now, but likely Postgresql in the future.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload