Module: ActsAsSaneTree::ClassMethods
- Defined in:
- lib/acts_as_sane_tree/acts_as_sane_tree.rb
Overview
Specify this acts_as
extension if you want to model a tree structure by providing a parent association and a children association. This requires that you have a foreign key column, which by default is called parent_id
.
class Category < ActiveRecord::Base
acts_as_sane_tree :order => "name"
end
Example:
root
\_ child1
\_ subchild1
\_ subchild2
root = Category.create("name" => "root")
child1 = root.children.create("name" => "child1")
subchild1 = child1.children.create("name" => "subchild1")
root.parent # => nil
child1.parent # => root
root.children # => [child1]
root.children.first.children.first # => subchild1
The following class methods are also added:
-
nodes_within?(src, chk)
- Returns true if chk contains any nodes found within src and all ancestors of nodes within src -
nodes_within(src, chk)
- Returns any matching nodes from chk found within src and all ancestors within src -
nodes_and_descendants(*args)
- Returns all nodes and descendants for given IDs or records. Accepts multiple IDs and records. Valid options:-
:raw - No Hash nesting
-
:no_self - Will not return given nodes in result set
-
=> n - Will set maximum depth to query
-
=> n - Alias for :depth
-
=> n - Will return times at given depth (takes precedence over :depth/:to_depth)
-
Instance Method Summary collapse
-
#acts_as_sane_tree(options = {}) ⇒ Object
Configuration options are:.
Instance Method Details
#acts_as_sane_tree(options = {}) ⇒ Object
Configuration options are:
-
foreign_key
- specifies the column name to use for tracking of the tree (default:parent_id
) -
order
- makes it possible to sort the children according to this SQL snippet. -
counter_cache
- keeps a count in achildren_count
column if set totrue
(default:false
).
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/acts_as_sane_tree/acts_as_sane_tree.rb', line 49 def acts_as_sane_tree( = {}) @configuration = {:foreign_key => :parent_id, :order => nil, :max_depth => 100000, :class => self, :dependent => :destroy, :parent_override => false} @configuration.update() if .is_a?(Hash) self.class_eval do cattr_accessor :configuration has_many :children, :class_name => @configuration[:class].name, :foreign_key => @configuration[:foreign_key], :order => @configuration[:order], :dependent => @configuration[:dependent] belongs_to :parent, :class_name => @configuration[:class].name, :foreign_key => @configuration[:foreign_key] if(@configuration[:parent_override]) def parent self.class.where(:id => self.parent_id).first end end validates_each @configuration[:foreign_key] do |record, attr, value| record.errors.add attr, 'cannot be own parent.' if !record.id.nil? && value.to_i == record.id.to_i end end self.configuration = @configuration include ActsAsSaneTree::InstanceMethods extend ActsAsSaneTree::SingletonMethods end |