module Sequel::Plugins::Tree

  1. lib/sequel/plugins/tree.rb

The tree plugin adds additional associations and methods that allow you to treat a Model as a tree.

A column for holding the parent key is required and is :parent_id by default.

This may be overridden by passing column name via :key.

Optionally, a column to control order of nodes returned can be specified by passing column name via :order.

If you pass true for the :single_root option, the class will ensure there is only ever one root in the tree.

Examples:

class Node < Sequel::Model
  plugin :tree
end

class Node < Sequel::Model
  plugin :tree, key: :parentid, order: :position
end

Methods

Public Class

  1. apply

Public Class methods

apply(model, opts=OPTS)

Create parent and children associations. Any options specified are passed to both associations. You can also specify options to use for just the parent association using a :parent option, and options to use for just the children association using a :children option.

[show source]
   # File lib/sequel/plugins/tree.rb
32 def self.apply(model, opts=OPTS)
33   opts = opts.dup
34   opts[:class] = model
35   opts[:key] ||= :parent_id
36 
37   par = opts.merge(opts.fetch(:parent, OPTS))
38   parent = par.fetch(:name, :parent)
39   
40   chi = opts.merge(opts.fetch(:children, OPTS))
41   children = chi.fetch(:name, :children)
42 
43   par[:reciprocal] = children
44   chi[:reciprocal] = parent
45 
46   model.instance_exec do
47     @parent_column = opts[:key]
48     @qualified_parent_column = Sequel.deep_qualify(table_name, opts[:key])
49     @tree_order = opts[:order]
50     @parent_association_name = parent
51     @children_association_name = children
52 
53     many_to_one parent, par
54     one_to_many children, chi
55     plugin SingleRoot if opts[:single_root]
56   end
57 end