mercredi 18 février 2015

Select objects where all children have no grandchildren

I have the following three-level hierarchy of models:



class Parent < AR::Base
has_many :children
end

class Child < AR::Base
has_many :grandchildren
belongs_to :parent

attr_accessible :my_number
end

class Grandchild < AR::Base
belongs_to :child
end


It is expected that all Parents will have multiple children, but each Child may or may not have any grandchildren.


I want to retrieve all Parent objects for which all the children have no grandchildren. How can I do this? I'd prefer a Rails-way, and I have squeel available; but I'll settle for raw SQL.


Bonus points if you can give me all Parent objects for which all the children have no grandchildren and all the children have my_number < 5.


Aucun commentaire:

Enregistrer un commentaire