module Sequel::Plugins::Tree
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
Public Class Methods
apply(model, opts=OPTS)
click to toggle source
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.
# File lib/sequel/plugins/tree.rb 32 def self.apply(model, opts=OPTS) 33 opts = opts.dup 34 opts[:class] = model 35 36 model.instance_exec do 37 @parent_column = (opts[:key] ||= :parent_id) 38 @tree_order = opts[:order] 39 end 40 41 par = opts.merge(opts.fetch(:parent, OPTS)) 42 parent = par.fetch(:name, :parent) 43 44 chi = opts.merge(opts.fetch(:children, OPTS)) 45 children = chi.fetch(:name, :children) 46 47 par[:reciprocal] = children 48 chi[:reciprocal] = parent 49 50 model.many_to_one parent, par 51 model.one_to_many children, chi 52 53 model.plugin SingleRoot if opts[:single_root] 54 end