[英]Rails: why is calling `valid?` only validate some of associated record not all associated records
[英]Rails query all records whose all associated record has nil or some specific value in some specific fields
我有两个具有has_many
和belongs_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.