After some trial and error I found that scope :roots, where(:parent_id => nil)
works just fine.
In Ruby, how to write an ActiveRecord named scope that finds the root nodes of a reflexive hierarchy?
-
01-06-2022 - |
Question
I have defined an ItemType
as follows:
class ItemType < ActiveRecord::Base
validates_presence_of :name
validates_uniqueness_of :name
has_many :items
has_many :children, :class_name => 'ItemType', :foreign_key => :parent_id
belongs_to :parent, :class_name => 'ItemType'
scope :roots, where("parent IS NULL")
end
but the named scope is not working.
How should I code this scope to return the ItemType
s that have no parents, ie the tree roots.
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow