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
  • 31,090
  • 47
  • 134
  • 244

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
  • 51,333
  • 10
  • 112
  • 145