我有两个模型:owner
和 pet
。一个主人 has_many :pets
和一只宠物 belongs_to :owner
。
我想做的是只捕获那些拥有所有重量超过 30 磅 宠物的主人。
#app/models/owner.rb
class Owner < ActiveRecord::Base
has_many :pets
#return only those owners that have heavy pets
end
#app/models/pet.rb
class Pet < ActiveRecord::Base
belongs_to :owner
scope :heavy, ->{ where(["weight > ?", 30])}
end
这是我的数据库中的内容。我有三个所有者:
- Neil,所有这些都很重;
- John,所有这些都不重;
- Bob,他的一些宠物很重,一些不重。
查询应该只返回 Neil。现在我的尝试返回 Neil 和 Bob。
最佳答案
您可以为每个 owner_id
组成一个组并检查,如果组中的所有行都符合要求的条件或者至少有一行不符合它,您可以实现它带有 group by
和 having
子句:
scope :heavy, -> { group("owner_id").having(["count(case when weight <= ? then weight end) = 0", 30]) }
还有另一种选择,更多的是 Rails-ActiveRecord 方法:
scope :heavy, -> { where.not(owner_id: Pet.where(["weight <= ?", 30]).distinct.pluck(:owner_id)).distinct }
在这里你得到所有不符合条件的 owner_id
(矛盾搜索),并将它们从原始查询的结果中排除。
关于sql - ActiveRecord:如果其中至少有一条记录不符合条件,则排除组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31117435/