Enrique Moreno Tent
Enrique Moreno Tent

Reputation: 25267

Query all instances of a model with 0 associations

I have a Model1and 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

Answers (2)

Athar
Athar

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

Pavan
Pavan

Reputation: 33542

You can do like this

@model2_ids = Model2.pluck(:model1_id)
@some_variable = Model1.where.not(id: @model2_ids)

Upvotes: 1

Related Questions