Module: Sequel::Plugins::Tree
- Defined in:
- lib/sequel/plugins/tree.rb
Overview
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
Defined Under Namespace
Modules: ClassMethods, InstanceMethods, SingleRoot Classes: TreeMultipleRootError
Class Method Summary collapse
-
.apply(model, opts = OPTS) ⇒ Object
Create parent and children associations.
Class Method Details
.apply(model, opts = OPTS) ⇒ Object
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.
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/sequel/plugins/tree.rb', line 32 def self.apply(model, opts=OPTS) opts = opts.dup opts[:class] = model model.instance_eval do @parent_column = (opts[:key] ||= :parent_id) @tree_order = opts[:order] end par = opts.merge(opts.fetch(:parent, {})) parent = par.fetch(:name, :parent) chi = opts.merge(opts.fetch(:children, {})) children = chi.fetch(:name, :children) par[:reciprocal] = children chi[:reciprocal] = parent model.many_to_one parent, par model.one_to_many children, chi model.plugin SingleRoot if opts[:single_root] end |