0

Possible Duplicate:
Rails 3 finding parents which have no child

I need to find all objects that does not have a nested object attached.

I'm aware of User.all.includes(:address) includes all with an "address" nested object but I'm not sure how to do the opposite.

The schema looks something like this. There's no User.address_id attribute.

User
has_one :address

Address
belongs_to :user
user_id: integer
address: string
Community
  • 1
  • 1
Martin
  • 10,926
  • 22
  • 82
  • 136

1 Answers1

1

Okay. I made a stupid mistake in the previous answer.

Here is a proper solution. You could do a query to find the Users with addresses then you can filter the Users without the address by passing the result of the previous query to another query.

Do this:

User.find_by_sql("SELECT * FROM users WHERE users.id NOT IN (SELECT users.id FROM users INNER JOIN addresses ON users.id=addresses.user_id)");

Btw this is a good question. Wonder why it was down voted.

Steve Robinson
  • 3,680
  • 3
  • 32
  • 54