ActiveRecord: Counting associations
I have two tables with a has_one <--> be开发者_如何转开发longs_to relationship: 'user' and 'account'. (An account must have a user, but a user need not have any accounts).
What I'd like to do is return all users who have no accounts...and I'm having a little trouble doing it gracefully. Is there a simple way to do this?
Many thanks...
You have to join the accounts table into the users table then check for an empty account. In Rails 3, you can do it like this:
User.includes(:account).where('accounts.id' => nil).all
In Rails 2, you can do it like this:
User.find(:all, :include => [ :account ], :conditions => { 'accounts.id' => nil })
精彩评论