Nick Ginanto
Nick Ginanto

Reputation: 32120

finding childrenless models in Rails

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?

Upvotes: 1

Views: 42

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52347

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

Upvotes: 3

Related Questions