forked from timothyjoh/acts_as_ordered_list
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathordered_tree.rb
60 lines (55 loc) · 1.96 KB
/
ordered_tree.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
55
56
57
58
59
60
require 'ordered_tree/class_methods'
require 'ordered_tree/instance_methods'
module OrderedTree #:nodoc:
# 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
def ordered_tree(options = {})
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[:primary_key] ||= :id
self.ordered_tree_config.update(options) if options.is_a?(Hash)
belongs_to(
:parent_node,
lambda { |instance| where(instance.send(:scope_condition)) },
:class_name => self.name,
:foreign_key => ordered_tree_config[:foreign_key],
:primary_key => ordered_tree_config[:primary_key],
)
has_many(
:child_nodes,
lambda { |instance|
where(instance.send(:scope_condition)).
order(ordered_tree_config[:order])
},
:class_name => self.name,
:foreign_key => ordered_tree_config[:foreign_key],
:primary_key => ordered_tree_config[:primary_key]
)
scope :roots, lambda { |*args|
column = "#{self.table_name}.#{self.ordered_tree_config[:foreign_key].to_sym}"
scope_condition = args[0]
where(scope_condition).
where("#{column} = 0 OR #{column} IS NULL").
order(self.ordered_tree_config[:order])
}
include OrderedTree::ClassMethods
include OrderedTree::InstanceMethods
end #ordered_tree
end #module OrderedTree
ActiveRecord::Base.extend OrderedTree