在 rails 3 中查找没有关联记录的记录 [英] Finding records with no associated records in rails 3
本文介绍了在 rails 3 中查找没有关联记录的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class Person < ActiveRecord::Base
has_many :pets
scope :with_dog, join(:pets).where("pets.type = 'Dog'")
scope :without_pets ???????????????????????????????????
end
class Pet < ActiveRecord::Base
belongs_to :people
end
我想向 Person 模型添加一个范围,以返回没有宠物的人.有任何想法吗?我觉得这很明显,但此刻它正在逃避我.
I'd like to add a scope to the Person model that returns people who have no pets. Any ideas? I feel like this is obvious, but it's escaping me at the moment.
推荐答案
试试这个:
Person.joins('left outer join pets on persons.id=pets.person_id').
select('persons.*,pets.id').
where('pets.id is null')
我还没有测试过,但它应该可以工作.
I haven't tested it but it ought to work.
这个想法是我们正在执行左外连接,因此对于每个没有宠物的人来说,pets 字段将为空.您可能需要包含 :readonly =>连接中的 false
,因为当 join()
传递一个字符串时,ActiveRecord 返回只读对象.
The idea is that we're performing a left outer join, so the pets fields will be null for every person that has no pets. You'll probably need to include :readonly => false
in the join since ActiveRecord returns read-only objects when join()
is passed a string.
这篇关于在 rails 3 中查找没有关联记录的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文