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?
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.