繁体   English   中英

Rails查询所有关联记录均为零或某些特定字段中具有特定值的所有记录

[英]Rails query all records whose all associated record has nil or some specific value in some specific fields

我有两个具有has_manybelongs_to关系的模型:

class Parent < ActiveRecord::Base
  has_many :children
end

class Child < ActiveRecord::Base
  belongs_to :parent
end

我如何找到所有在某些特定字段中所有子代都没有价值的父母。

您可以加入子表,然后检查您的attribute_to_test为零吗?

@nillish_parents = Parent.joins(:children).where("child.attribute_to_test IS ?", nil)

@nillish_parents.each do |p|
    p.name
end

“所有儿童都有病”通常要困难得多! 我敢肯定有一些方法可以处理复杂的联接,但是更简单的方法是执行以下操作:

parents = []
Parent.includes(:children).find_each do |parent|
  parents.push(parent) if parent.children.collect{|child| child.field.nil?}.reduce(:&)
end

暂无
暂无

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

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