class Customize::InheritNode < ActiveRecord::Base self.table_name = "customize_inherit_nodes" belongs_to :parent_node, :class_name=>self.name, :foreign_key=> 'parent_id' belongs_to :node, :polymorphic=>true has_many :children, :class_name=>self.name, :foreign_key=>'parent_id' has_many :ancestors, :class_name=>self.name, :finder_sql=> proc { %Q{ select distinct nodes.* from customize_inherit_nodes nodes where nodes.right > #{right} and nodes.left < #{left} and nodes.node_type = "#{node_type}" } } validates_presence_of :node_type, :node_id scope :by_type, lambda { |type| where(:node_type=>type) } after_destroy { |object| object.class.where("right > :right and node_type = :type", :right=>object.right, :type=>object.node_type).update_all("right = right -2") object.class.where("left > :right and node_type = :type", :right=>object.right, :type=>object.node_type).update_all("left = left -2") } before_create { |object| if object.parent_id.nil? left = self.class.where(:node_type=>object.node_type).maximum(:right) || -1 left = left + 1 object.left = left object.right = left + 1 else object.left = object.parent_node.right object.right = object.parent_node.right + 1 object.class.where("right >= :right and node_type = :type", :right=>object.left, :type=>object.node_type).update_all("right = right + 2") object.class.where("left >= :right and node_type = :type", :right=>object.right, :type=>object.node_type).update_all("left = left + 2") end } def leaf? children.empty? end end