Search code examples
ruby-on-railspostgresqlrelational-databasepg

How can I call a Parent with at least one Child of a Child relation?


I have a Parent object that has a child object, that can have many grandchild objects.

I am looking for an elegant scope for that works with PG to derive a Parent who has at least one grandchild object.

class Parent < ActiveRecord::Base
   has_many :childs
   # scope :has_grandchildren ...
end

class Child < ActiveRecord::Base
   has_many   :grandchilds
   belongs_to :parent
end

class Grandchild < ActiveRecord::Base
   belongs_to :child
end

Is this possible?


Solution

  • class Parent < ActiveRecord::Base
      has_many :childs
      has_many :grandchilds, :through => :childs
      scope    :has_grandchildren, childs.includes(:grandchilds).group("childs.id").having("count(grandchilds.id) < 0")
    end
    
    class Child < ActiveRecord::Base
      has_many   :grandchilds
      belongs_to :parent
    end
    
    class Grandchild < ActiveRecord::Base
      belongs_to :child
    end
    

    I added the has_many through relationship in case you needed it later, although it is optional.