Question

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?

Was it helpful?

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.

OTHER TIPS

I think you just want to do this. includes is an outer join. joins is an inner join which will exclude results that have 0 childs or 0 grandchilds.

class Parent < ActiveRecord::Base
  has_many :childs

  scope    :has_grandchildren, joins(:childs => :grandchilds).uniq
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top