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")
Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

  1. Robert Wilde Tue, 02 Nov 2010 10:39:26 UTC

    Thanks for that. I’ve used this to end on the getter methods on my Size model:

    class Size :variants, :conditions => { :variants => { :size_id => self.id } })
    end
    end

Comments