Module: EvenBetterNestedSet
- Defined in:
- lib/eb_nested_set.rb
Defined Under Namespace
Modules: NestedSet Classes: IllegalAssignmentError, NestedSetError
Instance Method Summary collapse
-
#acts_as_nested_set(options = {}) ⇒ Object
Declare this model as a nested set.
Instance Method Details
#acts_as_nested_set(options = {}) ⇒ Object
Declare this model as a nested set. Automatically adds all methods in EvenBetterNestedSet::NestedSet to the model, as well as parent and children associations.
Options
- left [Symbol]
-
the name of the column that contains the left boundary [Defaults to
left] - right [Symbol]
-
the name of the column that contains the right boundary [Defaults to
right] - scope [Symbol]
-
the name of an association to scope this nested set to
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/eb_nested_set.rb', line 18 def acts_as_nested_set(={}) = { :left => :left, :right => :right }.merge!() [:scope] = "#{[:scope]}_id" if [:scope] include NestedSet self. = class_eval <<-RUBY, __FILE__, __LINE__+1 def #{[:left]}=(left) raise EvenBetterNestedSet::IllegalAssignmentError, "#{[:left]} is an internal attribute used by EvenBetterNestedSet, do not assign it directly as is may corrupt the data in your database" end def #{[:right]}=(right) raise EvenBetterNestedSet::IllegalAssignmentError, "#{[:right]} is an internal attribute used by EvenBetterNestedSet, do not assign it directly as is may corrupt the data in your database" end RUBY named_scope :roots, :conditions => { :parent_id => nil }, :order => "#{nested_set_column(:left)} asc" has_many :children, :class_name => self.name, :foreign_key => :parent_id, :order => "#{nested_set_column(:left)} asc" belongs_to :parent, :class_name => self.name, :foreign_key => :parent_id named_scope :descendants, lambda { |node| left, right = find_boundaries(node.id) { :conditions => ["#{nested_set_column(:left)} > ? and #{nested_set_column(:right)} < ?", left, right], :order => "#{nested_set_column(:left)} asc" } } before_create :append_node before_update :move_node before_destroy :reload after_destroy :remove_node validate_on_update :illegal_nesting validate :validate_parent_is_within_scope delegate :nested_set_column, :to => "self.class" end |