Module: Edge::Forest::ActsAsForest

Defined in:
lib/edge/forest.rb

Overview

acts_as_forest models a tree/multi-tree structure.

Instance Method Summary collapse

Instance Method Details

#acts_as_forest(options = {}) ⇒ Object

options:

  • foreign_key - column name to use for parent foreign_key (default: parent_id)

  • order - how to order children (default: none)



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
# File 'lib/edge/forest.rb', line 9

def acts_as_forest(options={})
  options.assert_valid_keys :foreign_key, :order

  class_attribute :forest_foreign_key
  self.forest_foreign_key = options[:foreign_key] || "parent_id"

  class_attribute :forest_order
  self.forest_order = options[:order] || nil

  common_options = {
    :class_name => self,
    :foreign_key => forest_foreign_key
  }

  belongs_to :parent, common_options

  if forest_order
    has_many :children, -> { order(forest_order) }, common_options
  else
    has_many :children, common_options
  end

  scope :root, -> { where(forest_foreign_key => nil) }

  include Edge::Forest::InstanceMethods
  extend Edge::Forest::ClassMethods
end