Module: OrderedTree
- Defined in:
- lib/ordered_tree.rb,
lib/ordered_tree/class_methods.rb,
lib/ordered_tree/instance_methods.rb,
lib/ordered_tree/instance_methods/list.rb,
lib/ordered_tree/instance_methods/misc.rb,
lib/ordered_tree/instance_methods/tree.rb,
lib/ordered_tree/instance_methods/destroy.rb
Overview
:nodoc:
Defined Under Namespace
Modules: ClassMethods, InstanceMethods
Instance Method Summary collapse
-
#ordered_tree(options = {}) ⇒ Object
Configuration:.
Instance Method Details
#ordered_tree(options = {}) ⇒ Object
Configuration:
class Person < ActiveRecord::Base
ordered_tree :foreign_key => :parent_id,
:order => :position
end
class CreatePeople < ActiveRecord::Migration
def self.up
create_table :people do |t|
t.column :parent_id ,:integer ,:null => false ,:default => 0
t.column :position ,:integer
end
add_index(:people, :parent_id)
end
end
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 |
# File 'lib/ordered_tree.rb', line 22 def ordered_tree( = {}) cattr_accessor :ordered_tree_config self.ordered_tree_config ||= {} self.ordered_tree_config[:foreign_key] ||= :parent_id self.ordered_tree_config[:order] ||= :position self.ordered_tree_config.update() if .is_a?(Hash) belongs_to :parent_node, :class_name => self.name, :foreign_key => ordered_tree_config[:foreign_key] has_many :child_nodes, :class_name => self.name, :foreign_key => ordered_tree_config[:foreign_key], :order => ordered_tree_config[:order] scope :roots, lambda { |*args| scope_condition = args[0] where(scope_condition).where(self.ordered_tree_config[:foreign_key].to_sym => 0).order(self.ordered_tree_config[:order]) } # If the scope is something like :person, then turn it into :person_id if self.ordered_tree_config[:scope].is_a?(Symbol) && self.ordered_tree_config[:scope].to_s !~ /_id$/ self.ordered_tree_config[:scope] = "#{self.ordered_tree_config[:scope]}_id".intern end if self.ordered_tree_config[:scope].is_a?(Symbol) # ie :person_id define_method "scope_condition" do hash = {self.class.ordered_tree_config[:scope].to_sym => send(self.class.ordered_tree_config[:scope].to_sym)} self.class.send(:sanitize_sql_hash_for_conditions, hash) end end include OrderedTree::ClassMethods include OrderedTree::InstanceMethods end |