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
4

1 回答 1

1

好的。我在上一个答案中犯了一个愚蠢的错误。

这是一个适当的解决方案。您可以进行查询以查找具有地址的用户,然后您可以通过将先前查询的结果传递给另一个查询来过滤没有地址的用户。

做这个:

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

顺便说一句,这是一个很好的问题。想知道为什么它被否决了。

于 2012-11-19T09:00:00.110 回答