Module: IsTree::ActiveRecord::Tree::ClassMethods

Defined in:
lib/is_tree/active_record/tree.rb

Instance Method Summary collapse

Instance Method Details

#is_tree(options = {}) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/is_tree/active_record/tree.rb', line 11

def is_tree(options = {})
  configuration = { :foreign_key => "parent_id", :order => nil, :counter_cache => nil}
  configuration.merge!(options) if options.is_a?(Hash)
  
  has_many_params = {:order => configuration[:order]}.merge(configuration[:dependent] ? {:dependent => configuration[:dependent]} : {})
  association_params = {:class_name => self.name, :foreign_key => configuration[:foreign_key]}
  root_scope_params = {:conditions => {configuration[:foreign_key] => nil}, :order => configuration[:order]}
  
  belongs_to :parent, association_params.merge({:counter_cache => configuration[:counter_cache]})
  has_many :children, association_params.merge(has_many_params)
  
  named_scope :roots, root_scope_params
  named_scope :with_parent, {:include => :parent}
  named_scope :with_children, {:include => :children}
  
  self.class_eval do            
    include IsTree::ActiveRecord::Tree::InstanceMethods
    
    def self.root
      self.roots.first
    end
  end
  
end