开发者

ActiveRecord: Counting associations

开发者 https://www.devze.com 2023-02-05 13:51 出处:网络
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).

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 })
0

精彩评论

暂无评论...
验证码 换一张
取 消