Rails Join Query For Empty Right Tables

Posted on February 04, 2010

Say you wanted to select all the accounts from your applications with no associated users. You’d think this would be obvious, however I racked my brain for a few minutes thinking of a Rails-way of sorting this out.

The good news is with Rails 2.2 or later, it can be accomplished like this thanks to join hashes.

Company.find(:all, :include => :users,
             :conditions => { :users => { :id => nil } })

Before Rails 2.2, you would have had to resort to the following.

Company.find(:all, :include => :users,
             :conditions => "users.id IS NULL")