In Ruby, how to write an ActiveRecord named scope that finds the root nodes of a reflexive hierarchy?

StackOverflow https://stackoverflow.com/questions/17288427

Frage

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 ItemTypes that have no parents, ie the tree roots.

War es hilfreich?

Lösung

After some trial and error I found that scope :roots, where(:parent_id => nil) works just fine.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top