문제

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.

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top