试图提出一个范围,该范围将找到所有Parents
的Children
没有Pets
名为" Bob"
Parent.includes(children: :pets).where.not("pets.name = ?", "Bob")
会发现所有的父母都有一只宠物,而不是"鲍勃"以外的其他东西,但我想找到所有父母,那里没有一个宠物被命名为"鲍勃"
例如:
parent | child | pet.name
1 1 "Mr. Cat"
1 1 "Barker"
1 2 "Snuggles"
2 3 "Bob"
2 4 "Carl"
3 5 "Bob"
我希望查询仅返回父1,因为父母1的宠物有0个名为Bob的宠物。但是,范围却返回父母1和2。由于父母2的宠物叫" Carl"one_answers" Carl"!=" Bob"。
您可以使用 not Ilike
Parent.includes(children: :pets).where.not("pets.name not ilike ?", "%Bob%")
编辑代码
Parent.includes(children: :pets).where("pets.name not ilike ?", "%Bob%")