Reputation: 25267
I have a Model1
and a Model2
with an 1:N relationship (Model1 has_many Model2). How can I query all the instances of Model1
without any association with any Model2
?
Upvotes: 0
Views: 22
Reputation: 3268
considering table name of Model1 is model1
and table name of Model2 is model2
try this
Model1.joins("left outer join model2 on model2.model1_id = model1.id").where(model2: {model1_id: nil})
Upvotes: 0
Reputation: 33542
You can do like this
@model2_ids = Model2.pluck(:model1_id)
@some_variable = Model1.where.not(id: @model2_ids)
Upvotes: 1