Skip to content
Advertisement

Rails User.joins.not(…) in Active Record?

Im looking to query all Users without Comments in a single sql query?

Models:

So I want the opposite of this:

But not like this: (because it generates two queries)

Maybe something like this?

Thanks for any input!

Advertisement

Answer

You can accomplish this with:

This will result in raw SQL that looks something like:

For accomplishing this via a subquery, see the below answer.

Old Answer:

You can do something like

If you wanted a single (though nested) query.

Otherwise, check out http://guides.rubyonrails.org/active_record_querying.html#joining-tables for using an outer join.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement