### Home Classes Methods

### In Files

- lib/sequel/plugins/rcte_tree.rb

### Methods

- ::apply

### Files

- CHANGELOG
- MIT-LICENSE
- README.rdoc
- active_record.rdoc
- advanced_associations.rdoc
- association_basics.rdoc
- cheat_sheet.rdoc
- dataset_basics.rdoc
- dataset_filtering.rdoc
- mass_assignment.rdoc
- migration.rdoc
- model_hooks.rdoc
- opening_databases.rdoc
- prepared_statements.rdoc
- querying.rdoc
- reflection.rdoc
- 1.0.txt
- 1.1.txt
- 1.3.txt
- 1.4.0.txt
- 1.5.0.txt
- 2.0.0.txt
- 2.1.0.txt
- 2.10.0.txt
- 2.11.0.txt
- 2.12.0.txt
- 2.2.0.txt
- 2.3.0.txt
- 2.4.0.txt
- 2.5.0.txt
- 2.6.0.txt
- 2.7.0.txt
- 2.8.0.txt
- 2.9.0.txt
- 3.0.0.txt
- 3.1.0.txt
- 3.10.0.txt
- 3.11.0.txt
- 3.12.0.txt
- 3.13.0.txt
- 3.14.0.txt
- 3.15.0.txt
- 3.16.0.txt
- 3.17.0.txt
- 3.18.0.txt
- 3.19.0.txt
- 3.2.0.txt
- 3.20.0.txt
- 3.21.0.txt
- 3.22.0.txt
- 3.23.0.txt
- 3.24.0.txt
- 3.25.0.txt
- 3.26.0.txt
- 3.27.0.txt
- 3.28.0.txt
- 3.29.0.txt
- 3.3.0.txt
- 3.30.0.txt
- 3.31.0.txt
- 3.32.0.txt
- 3.33.0.txt
- 3.4.0.txt
- 3.5.0.txt
- 3.6.0.txt
- 3.7.0.txt
- 3.8.0.txt
- 3.9.0.txt
- schema_modification.rdoc
- sharding.rdoc
- sql.rdoc
- testing.rdoc
- transactions.rdoc
- validations.rdoc
- virtual_rows.rdoc

### Class Index

Quicksearch

- Sequel
- Sequel::ADO
- Sequel::ADO::Database
- Sequel::ADO::Dataset
- Sequel::ADO::MSSQL
- Sequel::ADO::MSSQL::DatabaseMethods
- Sequel::ADO::MSSQL::Dataset
- Sequel::ASTTransformer
- Sequel::Access
- Sequel::Access::DatabaseMethods
- Sequel::Access::DatasetMethods
- Sequel::Adapter
- Sequel::AdapterNotFound
- Sequel::AdapterNotFound
- Sequel::Amalgalite
- Sequel::Amalgalite::Database
- Sequel::Amalgalite::Dataset
- Sequel::Amalgalite::SequelTypeMap
- Sequel::ArbitraryServers
- Sequel::BasicObject
- Sequel::ColumnsIntrospection
- Sequel::ConnectionPool
- Sequel::ConnectionPool::ClassMethods
- Sequel::DB2
- Sequel::DB2::DB2Error
- Sequel::DB2::Database
- Sequel::DB2::DatabaseMethods
- Sequel::DB2::Dataset
- Sequel::DB2::DatasetMethods
- Sequel::DBI
- Sequel::DBI::Database
- Sequel::DBI::Dataset
- Sequel::DataObjects
- Sequel::DataObjects::Database
- Sequel::DataObjects::Dataset
- Sequel::DataObjects::MySQL
- Sequel::DataObjects::MySQL::DatabaseMethods
- Sequel::DataObjects::MySQL::Dataset
- Sequel::DataObjects::Postgres
- Sequel::DataObjects::Postgres::AdapterMethods
- Sequel::DataObjects::Postgres::DatabaseMethods
- Sequel::DataObjects::Postgres::Dataset
- Sequel::DataObjects::SQLite
- Sequel::DataObjects::SQLite::DatabaseMethods
- Sequel::DataObjects::SQLite::Dataset
- Sequel::Database
- Sequel::DatabaseConnectionError
- Sequel::DatabaseDisconnectError
- Sequel::DatabaseError
- Sequel::Dataset
- Sequel::Dataset
- Sequel::Dataset::ArgumentMapper
- Sequel::Dataset::BindArgumentMethods
- Sequel::Dataset::Pagination
- Sequel::Dataset::PreparedStatementMethods
- Sequel::Dataset::QueryBlockCopy
- Sequel::Dataset::StoredProcedureMethods
- Sequel::Dataset::StoredProcedures
- Sequel::Dataset::TYPE_TRANSLATOR
- Sequel::Dataset::UnnumberedArgumentMapper
- Sequel::EmulateOffsetWithRowNumber
- Sequel::Error
- Sequel::Firebird
- Sequel::Firebird::Database
- Sequel::Firebird::DatabaseMethods
- Sequel::Firebird::Dataset
- Sequel::Firebird::DatasetMethods
- Sequel::HookFailed
- Sequel::HookFailed
- Sequel::IBMDB
- Sequel::IBMDB::Connection
- Sequel::IBMDB::Connection::Error
- Sequel::IBMDB::Database
- Sequel::IBMDB::Dataset
- Sequel::IBMDB::Dataset::CallableStatementMethods
- Sequel::IBMDB::Dataset::PreparedStatementMethods
- Sequel::IBMDB::Statement
- Sequel::Inflections
- Sequel::Informix
- Sequel::Informix::Database
- Sequel::Informix::DatabaseMethods
- Sequel::Informix::Dataset
- Sequel::Informix::DatasetMethods
- Sequel::IntegerMigrator
- Sequel::InvalidOperation
- Sequel::InvalidOperation
- Sequel::InvalidValue
- Sequel::InvalidValue
- Sequel::JDBC
- Sequel::JDBC::AS400
- Sequel::JDBC::AS400::DatabaseMethods
- Sequel::JDBC::AS400::Dataset
- Sequel::JDBC::DB2
- Sequel::JDBC::DB2::DatabaseMethods
- Sequel::JDBC::DB2::Dataset
- Sequel::JDBC::Database
- Sequel::JDBC::Derby
- Sequel::JDBC::Derby::DatabaseMethods
- Sequel::JDBC::Derby::Dataset
- Sequel::JDBC::Firebird
- Sequel::JDBC::Firebird::DatabaseMethods
- Sequel::JDBC::Firebird::Dataset
- Sequel::JDBC::H2
- Sequel::JDBC::H2::DatabaseMethods
- Sequel::JDBC::H2::Dataset
- Sequel::JDBC::HSQLDB
- Sequel::JDBC::HSQLDB::DatabaseMethods
- Sequel::JDBC::HSQLDB::Dataset
- Sequel::JDBC::Informix
- Sequel::JDBC::Informix::DatabaseMethods
- Sequel::JDBC::Informix::Dataset
- Sequel::JDBC::JTDS
- Sequel::JDBC::JTDS::DatabaseMethods
- Sequel::JDBC::JTDS::Dataset
- Sequel::JDBC::JavaLang
- Sequel::JDBC::JavaSQL
- Sequel::JDBC::JavaxNaming
- Sequel::JDBC::MSSQL
- Sequel::JDBC::MSSQL::DatabaseMethods
- Sequel::JDBC::MySQL
- Sequel::JDBC::MySQL::DatabaseMethods
- Sequel::JDBC::MySQL::Dataset
- Sequel::JDBC::Oracle
- Sequel::JDBC::Oracle::DatabaseMethods
- Sequel::JDBC::Oracle::Dataset
- Sequel::JDBC::Postgres
- Sequel::JDBC::Postgres::AdapterMethods
- Sequel::JDBC::Postgres::DatabaseMethods
- Sequel::JDBC::Postgres::Dataset
- Sequel::JDBC::SQLServer
- Sequel::JDBC::SQLServer::DatabaseMethods
- Sequel::JDBC::SQLServer::DatabaseMethods::MetadataDatasetMethods
- Sequel::JDBC::SQLServer::Dataset
- Sequel::JDBC::SQLite
- Sequel::JDBC::SQLite::DatabaseMethods
- Sequel::JDBC::SQLite::Dataset
- Sequel::JDBC::Transactions
- Sequel::LiteralString
- Sequel::LooserTypecasting
- Sequel::MSSQL
- Sequel::MSSQL::DatabaseMethods
- Sequel::MSSQL::DatasetMethods
- Sequel::Metaprogramming
- Sequel::Migration
- Sequel::MigrationAlterTableReverser
- Sequel::MigrationDSL
- Sequel::MigrationReverser
- Sequel::Migrator
- Sequel::Migrator::Error
- Sequel::Mock
- Sequel::Mock::Connection
- Sequel::Mock::Database
- Sequel::Mock::Dataset
- Sequel::Model
- Sequel::Model::Associations
- Sequel::Model::Associations::AssociationDatasetMethods
- Sequel::Model::Associations::AssociationReflection
- Sequel::Model::Associations::ClassMethods
- Sequel::Model::Associations::DatasetMethods
- Sequel::Model::Associations::EagerGraphLoader
- Sequel::Model::Associations::InstanceMethods
- Sequel::Model::Associations::ManyToManyAssociationReflection
- Sequel::Model::Associations::ManyToOneAssociationReflection
- Sequel::Model::Associations::OneToManyAssociationReflection
- Sequel::Model::Associations::OneToOneAssociationReflection
- Sequel::Model::ClassMethods
- Sequel::Model::DatasetMethods
- Sequel::Model::Errors
- Sequel::Model::InstanceMethods
- Sequel::MySQL
- Sequel::MySQL::DatabaseMethods
- Sequel::MySQL::DatasetMethods
- Sequel::MySQL::DatasetMethods::CallableStatementMethods
- Sequel::MySQL::DatasetMethods::PreparedStatementMethods
- Sequel::MySQL::DatasetMethods::StoredProcedureMethods
- Sequel::MySQL::PreparedStatements
- Sequel::MySQL::PreparedStatements::DatabaseMethods
- Sequel::Mysql2
- Sequel::Mysql2::Database
- Sequel::Mysql2::Dataset
- Sequel::NamedTimezones
- Sequel::NoExistingObject
- Sequel::NoExistingObject
- Sequel::NotImplemented
- Sequel::ODBC
- Sequel::ODBC::DB2
- Sequel::ODBC::DB2::DatabaseMethods
- Sequel::ODBC::DB2::Dataset
- Sequel::ODBC::Database
- Sequel::ODBC::Dataset
- Sequel::ODBC::MSSQL
- Sequel::ODBC::MSSQL::DatabaseMethods
- Sequel::ODBC::MSSQL::Dataset
- Sequel::OpenBase
- Sequel::OpenBase::Database
- Sequel::OpenBase::Dataset
- Sequel::Oracle
- Sequel::Oracle::Database
- Sequel::Oracle::DatabaseMethods
- Sequel::Oracle::DatasetMethods
- Sequel::Plugins
- Sequel::Plugins::ActiveModel
- Sequel::Plugins::ActiveModel::ClassMethods
- Sequel::Plugins::ActiveModel::InstanceMethods
- Sequel::Plugins::AssociationAutoreloading
- Sequel::Plugins::AssociationAutoreloading::ClassMethods
- Sequel::Plugins::AssociationDependencies
- Sequel::Plugins::AssociationDependencies::ClassMethods
- Sequel::Plugins::AssociationDependencies::InstanceMethods
- Sequel::Plugins::AssociationPks
- Sequel::Plugins::AssociationPks::ClassMethods
- Sequel::Plugins::AssociationPks::InstanceMethods
- Sequel::Plugins::AssociationProxies
- Sequel::Plugins::AssociationProxies::AssociationProxy
- Sequel::Plugins::AssociationProxies::ClassMethods
- Sequel::Plugins::BooleanReaders
- Sequel::Plugins::BooleanReaders::ClassMethods
- Sequel::Plugins::Caching
- Sequel::Plugins::Caching::ClassMethods
- Sequel::Plugins::Caching::InstanceMethods
- Sequel::Plugins::ClassTableInheritance
- Sequel::Plugins::ClassTableInheritance::ClassMethods
- Sequel::Plugins::ClassTableInheritance::InstanceMethods
- Sequel::Plugins::Composition
- Sequel::Plugins::Composition::ClassMethods
- Sequel::Plugins::Composition::InstanceMethods
- Sequel::Plugins::DatasetAssociations
- Sequel::Plugins::DatasetAssociations::ClassMethods
- Sequel::Plugins::DatasetAssociations::DatasetMethods
- Sequel::Plugins::DefaultsSetter
- Sequel::Plugins::DefaultsSetter::ClassMethods
- Sequel::Plugins::DefaultsSetter::InstanceMethods
- Sequel::Plugins::ForceEncoding
- Sequel::Plugins::ForceEncoding::ClassMethods
- Sequel::Plugins::ForceEncoding::InstanceMethods
- Sequel::Plugins::HookClassMethods
- Sequel::Plugins::HookClassMethods::ClassMethods
- Sequel::Plugins::HookClassMethods::InstanceMethods
- Sequel::Plugins::IdentityMap
- Sequel::Plugins::IdentityMap::ClassMethods
- Sequel::Plugins::IdentityMap::InstanceMethods
- Sequel::Plugins::InstanceFilters
- Sequel::Plugins::InstanceFilters::InstanceMethods
- Sequel::Plugins::InstanceHooks
- Sequel::Plugins::InstanceHooks::InstanceMethods
- Sequel::Plugins::JsonSerializer
- Sequel::Plugins::JsonSerializer::ClassMethods
- Sequel::Plugins::JsonSerializer::DatasetMethods
- Sequel::Plugins::JsonSerializer::InstanceMethods
- Sequel::Plugins::JsonSerializer::Literal
- Sequel::Plugins::LazyAttributes
- Sequel::Plugins::LazyAttributes::ClassMethods
- Sequel::Plugins::LazyAttributes::InstanceMethods
- Sequel::Plugins::List
- Sequel::Plugins::List::ClassMethods
- Sequel::Plugins::List::InstanceMethods
- Sequel::Plugins::ManyThroughMany
- Sequel::Plugins::ManyThroughMany::ClassMethods
- Sequel::Plugins::ManyThroughMany::DatasetMethods
- Sequel::Plugins::ManyThroughMany::ManyThroughManyAssociationReflection
- Sequel::Plugins::NestedAttributes
- Sequel::Plugins::NestedAttributes::ClassMethods
- Sequel::Plugins::NestedAttributes::InstanceMethods
- Sequel::Plugins::OptimisticLocking
- Sequel::Plugins::OptimisticLocking::ClassMethods
- Sequel::Plugins::OptimisticLocking::InstanceMethods
- Sequel::Plugins::PreparedStatements
- Sequel::Plugins::PreparedStatements::ClassMethods
- Sequel::Plugins::PreparedStatements::InstanceMethods
- Sequel::Plugins::PreparedStatementsAssociations
- Sequel::Plugins::PreparedStatementsAssociations::ClassMethods
- Sequel::Plugins::PreparedStatementsAssociations::InstanceMethods
- Sequel::Plugins::PreparedStatementsSafe
- Sequel::Plugins::PreparedStatementsSafe::ClassMethods
- Sequel::Plugins::PreparedStatementsSafe::InstanceMethods
- Sequel::Plugins::PreparedStatementsWithPk
- Sequel::Plugins::PreparedStatementsWithPk::ClassMethods
- Sequel::Plugins::PreparedStatementsWithPk::DatasetMethods
- Sequel::Plugins::RcteTree
- Sequel::Plugins::Schema
- Sequel::Plugins::Schema::ClassMethods
- Sequel::Plugins::Serialization
- Sequel::Plugins::Serialization::ClassMethods
- Sequel::Plugins::Serialization::InstanceMethods
- Sequel::Plugins::SerializationModificationDetection
- Sequel::Plugins::SerializationModificationDetection::InstanceMethods
- Sequel::Plugins::Sharding
- Sequel::Plugins::Sharding::ClassMethods
- Sequel::Plugins::Sharding::DatasetMethods
- Sequel::Plugins::Sharding::InstanceMethods
- Sequel::Plugins::SingleTableInheritance
- Sequel::Plugins::SingleTableInheritance::ClassMethods
- Sequel::Plugins::SingleTableInheritance::InstanceMethods
- Sequel::Plugins::SkipCreateRefresh
- Sequel::Plugins::SkipCreateRefresh::InstanceMethods
- Sequel::Plugins::StringStripper
- Sequel::Plugins::StringStripper::InstanceMethods
- Sequel::Plugins::Subclasses
- Sequel::Plugins::Subclasses::ClassMethods
- Sequel::Plugins::TacticalEagerLoading
- Sequel::Plugins::TacticalEagerLoading::DatasetMethods
- Sequel::Plugins::TacticalEagerLoading::InstanceMethods
- Sequel::Plugins::Timestamps
- Sequel::Plugins::Timestamps::ClassMethods
- Sequel::Plugins::Timestamps::InstanceMethods
- Sequel::Plugins::Touch
- Sequel::Plugins::Touch::ClassMethods
- Sequel::Plugins::Touch::InstanceMethods
- Sequel::Plugins::Tree
- Sequel::Plugins::Tree::ClassMethods
- Sequel::Plugins::Tree::InstanceMethods
- Sequel::Plugins::Tree::SingleRoot
- Sequel::Plugins::Tree::SingleRoot::ClassMethods
- Sequel::Plugins::Tree::SingleRoot::InstanceMethods
- Sequel::Plugins::Tree::TreeMultipleRootError
- Sequel::Plugins::TypecastOnLoad
- Sequel::Plugins::TypecastOnLoad::ClassMethods
- Sequel::Plugins::TypecastOnLoad::InstanceMethods
- Sequel::Plugins::UpdatePrimaryKey
- Sequel::Plugins::UpdatePrimaryKey::ClassMethods
- Sequel::Plugins::UpdatePrimaryKey::InstanceMethods
- Sequel::Plugins::ValidationClassMethods
- Sequel::Plugins::ValidationClassMethods::ClassMethods
- Sequel::Plugins::ValidationClassMethods::ClassMethods::Generator
- Sequel::Plugins::ValidationClassMethods::InstanceMethods
- Sequel::Plugins::ValidationHelpers
- Sequel::Plugins::ValidationHelpers::InstanceMethods
- Sequel::Plugins::XmlSerializer
- Sequel::Plugins::XmlSerializer::ClassMethods
- Sequel::Plugins::XmlSerializer::DatasetMethods
- Sequel::Plugins::XmlSerializer::InstanceMethods
- Sequel::PoolTimeout
- Sequel::PoolTimeout
- Sequel::Postgres
- Sequel::Postgres::AdapterMethods
- Sequel::Postgres::DatabaseMethods
- Sequel::Postgres::DatasetMethods
- Sequel::Postgres::DatasetMethods::PreparedStatementMethods
- Sequel::PrettyTable
- Sequel::Progress
- Sequel::Progress::DatabaseMethods
- Sequel::Progress::DatasetMethods
- Sequel::Qualifier
- Sequel::Rollback
- Sequel::Rollback
- Sequel::SQL
- Sequel::SQL::AliasMethods
- Sequel::SQL::AliasedExpression
- Sequel::SQL::BitwiseMethods
- Sequel::SQL::Blob
- Sequel::SQL::BooleanConstant
- Sequel::SQL::BooleanExpression
- Sequel::SQL::BooleanMethods
- Sequel::SQL::CaseExpression
- Sequel::SQL::Cast
- Sequel::SQL::CastMethods
- Sequel::SQL::ColumnAll
- Sequel::SQL::ComplexExpression
- Sequel::SQL::ComplexExpressionMethods
- Sequel::SQL::Constant
- Sequel::SQL::Constants
- Sequel::SQL::Expression
- Sequel::SQL::Function
- Sequel::SQL::GenericComplexExpression
- Sequel::SQL::GenericExpression
- Sequel::SQL::Identifier
- Sequel::SQL::IdentifierMethods
- Sequel::SQL::InequalityMethods
- Sequel::SQL::JoinClause
- Sequel::SQL::JoinOnClause
- Sequel::SQL::JoinUsingClause
- Sequel::SQL::NegativeBooleanConstant
- Sequel::SQL::NoBooleanInputMethods
- Sequel::SQL::NumericExpression
- Sequel::SQL::NumericMethods
- Sequel::SQL::OrderMethods
- Sequel::SQL::OrderedExpression
- Sequel::SQL::PlaceholderLiteralString
- Sequel::SQL::QualifiedIdentifier
- Sequel::SQL::QualifyingMethods
- Sequel::SQL::StringConcatenationMethods
- Sequel::SQL::StringExpression
- Sequel::SQL::StringMethods
- Sequel::SQL::Subscript
- Sequel::SQL::SubscriptMethods
- Sequel::SQL::ValueList
- Sequel::SQL::ValueList
- Sequel::SQL::VirtualRow
- Sequel::SQL::Window
- Sequel::SQL::WindowFunction
- Sequel::SQLTime
- Sequel::SQLite
- Sequel::SQLite::DatabaseMethods
- Sequel::SQLite::DatasetMethods
- Sequel::Schema
- Sequel::Schema::AlterTableGenerator
- Sequel::Schema::Generator
- Sequel::ServerBlock
- Sequel::ShardedSingleConnectionPool
- Sequel::ShardedThreadedConnectionPool
- Sequel::SimpleMigration
- Sequel::SingleConnectionPool
- Sequel::Swift
- Sequel::Swift::Database
- Sequel::Swift::Dataset
- Sequel::Swift::MySQL
- Sequel::Swift::MySQL::DatabaseMethods
- Sequel::Swift::MySQL::Dataset
- Sequel::Swift::Postgres
- Sequel::Swift::Postgres::AdapterMethods
- Sequel::Swift::Postgres::DatabaseMethods
- Sequel::Swift::Postgres::Dataset
- Sequel::Swift::SQLite
- Sequel::Swift::SQLite::DatabaseMethods
- Sequel::Swift::SQLite::Dataset
- Sequel::ThreadLocalTimezones
- Sequel::ThreadedConnectionPool
- Sequel::ThreadedServerBlock
- Sequel::TimestampMigrator
- Sequel::Timezones
- Sequel::TinyTDS
- Sequel::TinyTDS::Database
- Sequel::TinyTDS::Dataset
- Sequel::TinyTDS::Dataset::ArgumentMapper
- Sequel::TinyTDS::Dataset::PreparedStatementMethods
- Sequel::ToDot
- Sequel::UnbindDuplicate
- Sequel::Unbinder
- Sequel::UndefinedAssociation
- Sequel::UnthreadedServerBlock
- Sequel::ValidationFailed
- Dataset
- Dataset::ArgumentMapper
- Dataset::BindArgumentMethods
- Dataset::PreparedStatementMethods
- String
- String::Inflections
- Array
- FalseClass
- Hash
- NilClass
- Numeric
- Object
- PGconn
- PGresult
- Proc
- Symbol
- TrueClass

No matching classes.

# Sequel::Plugins::RcteTree

# Overview

The rcte_tree plugin deals with tree structured data stored in the database using the adjacency list model (where child rows have a foreign key pointing to the parent rows), using recursive common table expressions to load all ancestors in a single query, all descendants in a single query, and all descendants to a given level (where level 1 is children, level 2 is children and grandchildren etc.) in a single query.

# Background

There are two types of common models for storing tree structured data in an SQL database, the adjacency list model and the nested set model. Before recursive common table expressions (or similar capabilities such as CONNECT BY for Oracle), the nested set model was the only easy way to retrieve all ancestors and descendants in a single query. However, it has significant performance corner cases.

On PostgreSQL 8.4, with a significant number of rows, the nested set model is almost 500 times slower than using a recursive common table expression with the adjacency list model to get all descendants, and almost 24,000 times slower to get all descendants to a given level.

Considering that the nested set model requires more difficult management than the adjacency list model, it’s almost always better to use the adjacency list model if your database supports common table expressions. See explainextended.com/2009/09/24/adjacency-list-vs-nested-sets-postgresql/ for detailed analysis.

# Usage

The rcte_tree plugin adds four associations to the model: parent, children, ancestors, and descendants. Both the parent and children are fairly standard many_to_one and one_to_many associations, respectively. However, the ancestors and descendants associations are special. Both the ancestors and descendants associations will automatically set the parent and children associations, respectively, for current object and all of the ancestor or descendant objects, whenever they are loaded (either eagerly or lazily). Additionally, the descendants association can take a level argument when called eagerly, which limits the returned objects to only that many levels in the tree (see the Overview).

      Model.plugin :rcte_tree

      # Lazy loading
      model = Model.first
      model.parent
      model.children
      model.ancestors # Populates :parent association for all ancestors
      model.descendants # Populates :children association for all descendants

      # Eager loading - also populates the :parent and children associations
      # for all ancestors and descendants
      Model.filter(:id=>[1, 2]).eager(:ancestors, :descendants).all

      # Eager loading children and grand children
      Model.filter(:id=>[1, 2]).eager(:descendants=>2).all
      # Eager loading children, grand children, and great grand children
      Model.filter(:id=>[1, 2]).eager(:descendants=>3).all

# Options

You can override the options for any specific association by making sure the plugin options contain one of the following keys:

- :parent - hash of options for the parent association

- :children - hash of options for the children association

- :ancestors - hash of options for the ancestors association

- :descendants - hash of options for the descendants association

Note that you can change the name of the above associations by specifying a :name key in the appropriate hash of options above. For example:

      Model.plugin :rcte_tree, :parent=>{:name=>:mother},
       :children=>{:name=>:daughters}, :descendants=>{:name=>:offspring}

Any other keys in the main options hash are treated as options shared by all of the associations. Here’s a few options that affect the plugin:

- :key - The foreign key in the table that points to the primary key of the parent (default: :parent_id)

- :primary_key - The primary key to use (default: the model’s primary key)

- :key_alias - The symbol identifier to use for aliasing when eager loading (default: :x_root_x)

- :cte_name - The symbol identifier to use for the common table expression (default: :t)

- :level_alias - The symbol identifier to use when eagerly loading descendants up to a given level (default: :x_level_x)

### Public Class Methods

apply(model, opts={}) click to toggle source

Create the appropriate parent, children, ancestors, and descendants associations for the model.

         # File lib/sequel/plugins/rcte_tree.rb, line 95
     95:       def self.apply(model, opts={})
     96:         model.plugin :tree, opts
     97:
     98:         opts = opts.dup
     99:         opts[:class] = model
    100:         opts[:methods_module] = Module.new
    101:         model.send(:include, opts[:methods_module])
    102:
    103:         key = opts[:key] ||= :parent_id
    104:         prkey = opts[:primary_key] ||= model.primary_key
    105:
    106:         parent = opts.merge(opts.fetch(:parent, {})).fetch(:name, :parent)
    107:         childrena = opts.merge(opts.fetch(:children, {})).fetch(:name, :children)
    108:
    109:         ka = opts[:key_alias] ||= :x_root_x
    110:         t = opts[:cte_name] ||= :t
    111:         opts[:reciprocal] = nil
    112:         c_all = if model.dataset.recursive_cte_requires_column_aliases?
    113:           # Work around Oracle/ruby-oci8 bug that returns integers as BigDecimals in recursive queries.
    114:           conv_bd = model.db.database_type == :oracle
    115:           col_aliases = model.dataset.columns
    116:           model_table = model.table_name
    117:           col_aliases.map{|c| SQL::QualifiedIdentifier.new(model_table, c)}
    118:         else
    119:           [SQL::ColumnAll.new(model.table_name)]
    120:         end
    121:
    122:         a = opts.merge(opts.fetch(:ancestors, {}))
    123:         ancestors = a.fetch(:name, :ancestors)
    124:         a[:read_only] = true unless a.has_key?(:read_only)
    125:         a[:eager_loader_key] = key
    126:         a[:dataset] ||= proc do
    127:           base_ds = model.filter(prkey=>send(key))
    128:           recursive_ds = model.join(t, key=>prkey)
    129:           if c = a[:conditions]
    130:             (base_ds, recursive_ds) = [base_ds, recursive_ds].collect do |ds|
    131:               (c.is_a?(Array) && !Sequel.condition_specifier?(c)) ? ds.filter(*c) : ds.filter(c)
    132:             end
    133:           end
    134:           table_alias = model.dataset.schema_and_table(model.table_name)[1].to_sym
    135:           model.from(t => table_alias).
    136:            with_recursive(t, col_aliases ? base_ds.select(*col_aliases) : base_ds.select_all,
    137:             recursive_ds.select(*c_all),
    138:             :args=>col_aliases)
    139:         end
    140:         aal = Array(a[:after_load])
    141:         aal << proc do |m, ancs|
    142:           unless m.associations.has_key?(parent)
    143:             parent_map = {m[prkey]=>m}
    144:             child_map = {}
    145:             child_map[m[key]] = m if m[key]
    146:             m.associations[parent] = nil
    147:             ancs.each do |obj|
    148:               obj.associations[parent] = nil
    149:               parent_map[obj[prkey]] = obj
    150:               if ok = obj[key]
    151:                 child_map[ok] = obj
    152:               end
    153:             end
    154:             parent_map.each do |parent_id, obj|
    155:               if child = child_map[parent_id]
    156:                 child.associations[parent] = obj
    157:               end
    158:             end
    159:           end
    160:         end
    161:         a[:after_load] ||= aal
    162:         a[:eager_loader] ||= proc do |eo|
    163:           id_map = eo[:key_hash][key]
    164:           parent_map = {}
    165:           children_map = {}
    166:           eo[:rows].each do |obj|
    167:             parent_map[obj[prkey]] = obj
    168:             (children_map[obj[key]] ||= []) << obj
    169:             obj.associations[ancestors] = []
    170:             obj.associations[parent] = nil
    171:           end
    172:           r = model.association_reflection(ancestors)
    173:           base_case = model.filter(prkey=>id_map.keys).
    174:            select(SQL::AliasedExpression.new(prkey, ka), *c_all)
    175:           recursive_case = model.join(t, key=>prkey).
    176:            select(SQL::QualifiedIdentifier.new(t, ka), *c_all)
    177:           if c = r[:conditions]
    178:             (base_case, recursive_case) = [base_case, recursive_case].collect do |ds|
    179:               (c.is_a?(Array) && !Sequel.condition_specifier?(c)) ? ds.filter(*c) : ds.filter(c)
    180:             end
    181:           end
    182:           table_alias = model.dataset.schema_and_table(model.table_name)[1].to_sym
    183:           elds = model.eager_loading_dataset(r,
    184:            model.from(t => table_alias).
    185:             with_recursive(t, base_case,
    186:              recursive_case,
    187:              :args=>(([ka] + col_aliases) if col_aliases)),
    188:            r.select,
    189:            eo[:associations], eo)
    190:           elds = elds.select_append(ka) unless elds.opts[:select] == nil
    191:           elds.all do |obj|
    192:             opk = obj[prkey]
    193:             if in_pm = parent_map.has_key?(opk)
    194:               if idm_obj = parent_map[opk]
    195:                 idm_obj.values[ka] = obj.values[ka]
    196:                 obj = idm_obj
    197:               end
    198:             else
    199:               obj.associations[parent] = nil
    200:               parent_map[opk] = obj
    201:               (children_map[obj[key]] ||= []) << obj
    202:             end
    203:
    204:             kv = obj.values.delete(ka)
    205:             kv = kv.to_i if conv_bd && kv.is_a?(BigDecimal)
    206:             if roots = id_map[kv]
    207:               roots.each do |root|
    208:                 root.associations[ancestors] << obj
    209:               end
    210:             end
    211:           end
    212:           parent_map.each do |parent_id, obj|
    213:             if children = children_map[parent_id]
    214:               children.each do |child|
    215:                 child.associations[parent] = obj
    216:               end
    217:             end
    218:           end
    219:         end
    220:         model.one_to_many ancestors, a
    221:
    222:         d = opts.merge(opts.fetch(:descendants, {}))
    223:         descendants = d.fetch(:name, :descendants)
    224:         d[:read_only] = true unless d.has_key?(:read_only)
    225:         la = d[:level_alias] ||= :x_level_x
    226:         d[:dataset] ||= proc do
    227:           base_ds = model.filter(key=>send(prkey))
    228:           recursive_ds = model.join(t, prkey=>key)
    229:           if c = d[:conditions]
    230:             (base_ds, recursive_ds) = [base_ds, recursive_ds].collect do |ds|
    231:               (c.is_a?(Array) && !Sequel.condition_specifier?(c)) ? ds.filter(*c) : ds.filter(c)
    232:             end
    233:           end
    234:           table_alias = model.dataset.schema_and_table(model.table_name)[1].to_sym
    235:           model.from(t => table_alias).
    236:            with_recursive(t, col_aliases ? base_ds.select(*col_aliases) : base_ds.select_all,
    237:             recursive_ds.select(*c_all),
    238:             :args=>col_aliases)
    239:           end
    240:         dal = Array(d[:after_load])
    241:         dal << proc do |m, descs|
    242:           unless m.associations.has_key?(childrena)
    243:             parent_map = {m[prkey]=>m}
    244:             children_map = {}
    245:             m.associations[childrena] = []
    246:             descs.each do |obj|
    247:               obj.associations[childrena] = []
    248:               if opk = obj[prkey]
    249:                 parent_map[opk] = obj
    250:               end
    251:               if ok = obj[key]
    252:                 (children_map[ok] ||= []) << obj
    253:               end
    254:             end
    255:             children_map.each do |parent_id, objs|
    256:               parent_map[parent_id].associations[childrena] = objs
    257:             end
    258:           end
    259:         end
    260:         d[:after_load] = dal
    261:         d[:eager_loader] ||= proc do |eo|
    262:           id_map = eo[:key_hash][prkey]
    263:           associations = eo[:associations]
    264:           parent_map = {}
    265:           children_map = {}
    266:           eo[:rows].each do |obj|
    267:             parent_map[obj[prkey]] = obj
    268:             obj.associations[descendants] = []
    269:             obj.associations[childrena] = []
    270:           end
    271:           r = model.association_reflection(descendants)
    272:           base_case = model.filter(key=>id_map.keys).
    273:            select(SQL::AliasedExpression.new(key, ka), *c_all)
    274:           recursive_case = model.join(t, prkey=>key).
    275:            select(SQL::QualifiedIdentifier.new(t, ka), *c_all)
    276:           if c = r[:conditions]
    277:             (base_case, recursive_case) = [base_case, recursive_case].collect do |ds|
    278:               (c.is_a?(Array) && !Sequel.condition_specifier?(c)) ? ds.filter(*c) : ds.filter(c)
    279:             end
    280:           end
    281:           if associations.is_a?(Integer)
    282:             level = associations
    283:             no_cache_level = level - 1
    284:             associations = {}
    285:             base_case = base_case.select_more(SQL::AliasedExpression.new(0, la))
    286:             recursive_case = recursive_case.select_more(SQL::AliasedExpression.new(SQL::QualifiedIdentifier.new(t, la) + 1, la)).filter(SQL::QualifiedIdentifier.new(t, la) < level - 1)
    287:           end
    288:           table_alias = model.dataset.schema_and_table(model.table_name)[1].to_sym
    289:           elds = model.eager_loading_dataset(r,
    290:            model.from(t => table_alias).with_recursive(t, base_case, recursive_case,
    291:             :args=>(([ka] + col_aliases + (level ? [la] : [])) if col_aliases)),
    292:            r.select,
    293:            associations, eo)
    294:           elds = elds.select_append(ka) unless elds.opts[:select] == nil
    295:           elds.all do |obj|
    296:             if level
    297:               no_cache = no_cache_level == obj.values.delete(la)
    298:             end
    299:
    300:             opk = obj[prkey]
    301:             if in_pm = parent_map.has_key?(opk)
    302:               if idm_obj = parent_map[opk]
    303:                 idm_obj.values[ka] = obj.values[ka]
    304:                 obj = idm_obj
    305:               end
    306:             else
    307:               obj.associations[childrena] = [] unless no_cache
    308:               parent_map[opk] = obj
    309:             end
    310:
    311:             kv = obj.values.delete(ka)
    312:             kv = kv.to_i if conv_bd && kv.is_a?(BigDecimal)
    313:             if root = id_map[kv].first
    314:               root.associations[descendants] << obj
    315:             end
    316:
    317:             (children_map[obj[key]] ||= []) << obj
    318:           end
    319:           children_map.each do |parent_id, objs|
    320:             parent_map[parent_id].associations[childrena] = objs.uniq
    321:           end
    322:         end
    323:         model.one_to_many descendants, d
    324:       end

Disabled; run with --debug to generate this.

[Validate]

Generated with the Darkfish Rdoc Generator 1.1.6.