简体   繁体   中英

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

I have two models with a has_many and belongs_to relations:

class Parent < ActiveRecord::Base
  has_many :children
end

class Child < ActiveRecord::Base
  belongs_to :parent
end

How do I find all those Parents whose all children have nil value in some specific field.

Can you join the child table and then check for your attribute_to_test being nil?

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

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

'All children have a condition' is generally much harder! I'm sure there's some way to do it with a complicated joins, but the easier ruby way is to do something like the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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