EDIT: Removed .all , added references and added use of arel_table
Items.joins(:organization).includes(:owners).references(:owners). where('owners.id IS NULL')
And if you want to use includes for both:
Items.includes(:organization, :owners).references(:organization, :owners). where('organisations.id IS NOT NULL AND owners.id IS NULL')
And, as @Dario Barrionuevo wrote, it should belong
Using arel_table in the first example:
Items.joins(:organization).includes(:owners).references(:owners). where(Owner.arel_table[:id].eq(nil))
In Rails 5 (from @aNoble comment):
Items.joins(:organization).left_joins(:owners). where(Owner.arel_table[:id].eq(nil))
But using includes is still preferable if links should be referenced in code to avoid extra readings.
244an source share