繁体   English   中英

查找导轨中没有关联记录的记录3

[英]Finding records with no associated records in 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模型中添加一个范围,以返回没有宠物的人。 有任何想法吗? 我觉得这很明显,但此刻正在逃避。

scope :without_pets, lambda { includes(:pets).where('pets.id' => nil) }

尝试这样的事情:

Person.joins('left outer join pets on persons.id=pets.person_id').
       select('persons.*,pets.id').
       where('pets.id is null')

我没有测试过,但它应该可以工作。

这个想法是,我们正在执行左外部联接,因此对于没有宠物的每个人,宠物字段将为null。 您可能需要在连接中包括:readonly => false ,因为Activejoin在传递join()字符串时会返回只读对象。

马克·韦斯特林的答案是正确的。 外部联接是正确的方法。 内部联接(如果您向其传递关联的名称/符号而不是您自己的SQL,则为joins方法生成的联接)将不起作用,因为它将不包含没有宠物的人。

在这里它被写为一个范围:

scope :without_pets, joins("left outer join pets on pets.person_id = persons.id").where("pets.id is null")

(如果这样不起作用,请尝试用“ people”替换“ persons”-我不确定您的表名是什么。)

您必须使用LEFT OUTER JOIN才能找到没有关联记录的记录。 这是我使用的代码的改编版本:

scope :without_pets, joins('LEFT OUTER JOIN pets ON people.id = pets.person_id').group('people.id').having('count(pets.id) = 0')

我不确定您的宠物模型是否有个人身份证,但也许这种尝试可以帮助您

scope :with_dog, joins(:pets).where("pets.type = 'Dog'")
scope :without_pets, joins(:pets).where("pets.person_id != persons.id")

更新:将查询方法名称从“ join”更正为“ joins”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM