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

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

문제

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.

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top