1

I have a self-association in a model

belongs_to :parent, class_name: "Person"
has_many :children, foreign_key: :parent_id, class_name: "Person"

getting the parents with where(parent_id: nil)

How do I get all person models with no children as a scope?

Nick Ginanto
  • 29,034
  • 41
  • 131
  • 227

1 Answers1

3

Try this out:

scope :with_no_children, -> { includes(:children).where(children: { id: nil }) } # or children_items: { id: nil } if that's self-referencing association

Reference

Community
  • 1
  • 1
Andrey Deineko
  • 49,444
  • 10
  • 105
  • 134