### Home Classes Methods

### In Files

- lib/sequel/model/associations.rb

### Methods

- ::extended
- #association_filter_expression
- #association_filter_handle_inversion
- #association_filter_key_expression
- #check_association
- #complex_expression_sql_append
- #eager
- #eager_graph
- #eager_graph_association
- #eager_graph_associations
- #eager_graph_build_associations
- #eager_load
- #graph_each
- #many_to_many_association_filter_expression
- #many_to_one_association_filter_expression
- #one_to_many_association_filter_expression
- #one_to_one_association_filter_expression
- #post_load
- #ungraphed

### 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::Model::Associations::DatasetMethods

Eager loading makes it so that you can load all associated records for a set of objects in a single query, instead of a separate query for each object.

Two separate implementations are provided. `eager` should be used most of the time, as it loads associated records using one query per association. However, it does not allow you the ability to filter or order based on columns in associated tables. `eager_graph` loads all records in a single query using JOINs, allowing you to filter or order based on columns in associated tables. However, `eager_graph` is usually slower than `eager`, especially if multiple one_to_many or many_to_many associations are joined.

You can cascade the eager loading (loading associations on associated objects) with no limit to the depth of the cascades. You do this by passing a hash to `eager` or `eager_graph` with the keys being associations of the current model and values being associations of the model associated with the current model via the key.

The arguments can be symbols or hashes with symbol keys (for cascaded eager loading). Examples:

      Album.eager(:artist).all
      Album.eager_graph(:artist).all
      Album.eager(:artist, :genre).all
      Album.eager_graph(:artist, :genre).all
      Album.eager(:artist).eager(:genre).all
      Album.eager_graph(:artist).eager(:genre).all
      Artist.eager(:albums=>:tracks).all
      Artist.eager_graph(:albums=>:tracks).all
      Artist.eager(:albums=>{:tracks=>:genre}).all
      Artist.eager_graph(:albums=>{:tracks=>:genre}).all

You can also pass a callback as a hash value in order to customize the dataset being eager loaded at query time, analogous to the way the :eager_block association option allows you to customize it at association definition time. For example, if you wanted artists with their albums since 1990:

      Artist.eager(:albums => proc{|ds| ds.filter{year > 1990}})

Or if you needed albums and their artist’s name only, using a single query:

      Albums.eager_graph(:artist => proc{|ds| ds.select(:name)})

To cascade eager loading while using a callback, you substitute the cascaded associations with a single entry hash that has the proc callback as the key and the cascaded associations as the value. This will load artists with their albums since 1990, and also the tracks on those albums and the genre for those tracks:

      Artist.eager(:albums => {proc{|ds| ds.filter{year > 1990}}=>{:tracks => :genre}})

### Public Class Methods

extended(obj) click to toggle source

Add the `eager!` and `eager_graph!` mutation methods to the dataset.

          # File lib/sequel/model/associations.rb, line 1671
    1671:         def self.extended(obj)
    1672:           obj.def_mutation_method(:eager, :eager_graph)
    1673:         end

### Public Instance Methods

complex_expression_sql_append(sql, op, args) click to toggle source

If the expression is in the form `x = y` where `y` is a `Sequel::Model` instance, array of `Sequel::Model` instances, or a `Sequel::Model` dataset, assume `x` is an association symbol and look up the association reflection via the dataset’s model. From there, return the appropriate SQL based on the type of association and the values of the foreign/primary keys of `y`. For most association types, this is a simple transformation, but for `many_to_many` associations this creates a subquery to the join table.

          # File lib/sequel/model/associations.rb, line 1682
    1682:         def complex_expression_sql_append(sql, op, args)
    1683:           r = args.at(1)
    1684:           if (((op == :'=' || op == :'!=') and r.is_a?(Sequel::Model)) ||
    1685:               (multiple = ((op == :IN || op == :'NOT IN') and ((is_ds = r.is_a?(Sequel::Dataset)) or r.all?{|x| x.is_a?(Sequel::Model)}))))
    1686:             l = args.at(0)
    1687:             if ar = model.association_reflections[l]
    1688:               if multiple
    1689:                 klass = ar.associated_class
    1690:                 if is_ds
    1691:                   if r.respond_to?(:model)
    1692:                     unless r.model <= klass
    1693:                       # A dataset for a different model class, could be a valid regular query
    1694:                       return super
    1695:                     end
    1696:                   else
    1697:                     # Not a model dataset, could be a valid regular query
    1698:                     return super
    1699:                   end
    1700:                 else
    1701:                   unless r.all?{|x| x.is_a?(klass)}
    1702:                     raise Sequel::Error, "invalid association class for one object for association #{l.inspect} used in dataset filter for model #{model.inspect}, expected class #{klass.inspect}"
    1703:                   end
    1704:                 end
    1705:               elsif !r.is_a?(ar.associated_class)
    1706:                 raise Sequel::Error, "invalid association class #{r.class.inspect} for association #{l.inspect} used in dataset filter for model #{model.inspect}, expected class #{ar.associated_class.inspect}"
    1707:               end
    1708:
    1709:               if exp = association_filter_expression(op, ar, r)
    1710:                 literal_append(sql, exp)
    1711:               else
    1712:                 raise Sequel::Error, "invalid association type #{ar[:type].inspect} for association #{l.inspect} used in dataset filter for model #{model.inspect}"
    1713:               end
    1714:             elsif multiple && (is_ds || r.empty?)
    1715:               # Not a query designed for this support, could be a valid regular query
    1716:               super
    1717:             else
    1718:               raise Sequel::Error, "invalid association #{l.inspect} used in dataset filter for model #{model.inspect}"
    1719:             end
    1720:           else
    1721:             super
    1722:           end
    1723:         end

eager(*associations) click to toggle source

The preferred eager loading method. Loads all associated records using one query for each association.

The basic idea for how it works is that the dataset is first loaded normally. Then it goes through all associations that have been specified via `eager`. It loads each of those associations separately, then associates them back to the original dataset via primary/foreign keys. Due to the necessity of all objects being present, you need to use `all` to use eager loading, as it can’t work with `each`.

This implementation avoids the complexity of extracting an object graph out of a single dataset, by building the object graph out of multiple datasets, one for each association. By using a separate dataset for each association, it avoids problems such as aliasing conflicts and creating cartesian product result sets if multiple one_to_many or many_to_many eager associations are requested.

One limitation of using this method is that you cannot filter the dataset based on values of columns in an associated table, since the associations are loaded in separate queries. To do that you need to load all associations in the same query, and extract an object graph from the results of that query. If you need to filter based on columns in associated tables, look at `eager_graph` or join the tables you need to filter on manually.

Each association’s order, if defined, is respected. Eager also works on a limited dataset, but does not use any :limit options for associations. If the association uses a block or has an :eager_block argument, it is used.

          # File lib/sequel/model/associations.rb, line 1751
    1751:         def eager(*associations)
    1752:           opt = @opts[:eager]
    1753:           opt = opt ? opt.dup : {}
    1754:           associations.flatten.each do |association|
    1755:             case association
    1756:               when Symbol
    1757:                 check_association(model, association)
    1758:                 opt[association] = nil
    1759:               when Hash
    1760:                 association.keys.each{|assoc| check_association(model, assoc)}
    1761:                 opt.merge!(association)
    1762:               else raise(Sequel::Error, 'Associations must be in the form of a symbol or hash')
    1763:             end
    1764:           end
    1765:           clone(:eager=>opt)
    1766:         end

eager_graph(*associations) click to toggle source

The secondary eager loading method. Loads all associations in a single query. This method should only be used if you need to filter or order based on columns in associated tables.

This method uses `Dataset#graph` to create appropriate aliases for columns in all the tables. Then it uses the graph’s metadata to build the associations from the single hash, and finally replaces the array of hashes with an array model objects inside all.

Be very careful when using this with multiple one_to_many or many_to_many associations, as you can create large cartesian products. If you must graph multiple one_to_many and many_to_many associations, make sure your filters are narrow if you have a large database.

Each association’s order, if definied, is respected. `eager_graph` probably won’t work correctly on a limited dataset, unless you are only graphing many_to_one and one_to_one associations.

Does not use the block defined for the association, since it does a single query for all objects. You can use the :graph_* association options to modify the SQL query.

Like `eager`, you need to call `all` on the dataset for the eager loading to work. If you just call `each`, it will yield plain hashes, each containing all columns from all the tables.

          # File lib/sequel/model/associations.rb, line 1788
    1788:         def eager_graph(*associations)
    1789:           ds = if eg = @opts[:eager_graph]
    1790:             eg = eg.dup
    1791:             [:requirements, :reflections, :reciprocals].each{|k| eg[k] = eg[k].dup}
    1792:             clone(:eager_graph=>eg)
    1793:           else
    1794:             # Each of the following have a symbol key for the table alias, with the following values:
    1795:             # :reciprocals - the reciprocal instance variable to use for this association
    1796:             # :reflections - AssociationReflection instance related to this association
    1797:             # :requirements - array of requirements for this association
    1798:             clone(:eager_graph=>{:requirements=>{}, :master=>alias_symbol(first_source), :reflections=>{}, :reciprocals=>{}, :cartesian_product_number=>0})
    1799:           end
    1800:           ds.eager_graph_associations(ds, model, ds.opts[:eager_graph][:master], [], *associations)
    1801:         end

ungraphed() click to toggle source

Do not attempt to split the result set into associations, just return results as simple objects. This is useful if you want to use eager_graph as a shortcut to have all of the joins and aliasing set up, but want to do something else with the dataset.

          # File lib/sequel/model/associations.rb, line 1807
    1807:         def ungraphed
    1808:           super.clone(:eager_graph=>nil)
    1809:         end

### Protected Instance Methods

eager_graph_association(ds, model, ta, requirements, r, *associations) click to toggle source

Call graph on the association with the correct arguments, update the eager_graph data structure, and recurse into eager_graph_associations if there are any passed in associations (which would be dependencies of the current association)

Arguments:

ds | Current dataset
model | Current Model
ta | table_alias used for the parent association
requirements | an array, used as a stack for requirements
r | association reflection for the current association
*associations | any associations dependent on this one

          # File lib/sequel/model/associations.rb, line 1825
    1825:         def eager_graph_association(ds, model, ta, requirements, r, *associations)
    1826:           assoc_name = r[:name]
    1827:           assoc_table_alias = ds.unused_table_alias(r[:graph_alias_base])
    1828:           loader = r[:eager_grapher]
    1829:           if !associations.empty?
    1830:             if associations.first.respond_to?(:call)
    1831:               callback = associations.first
    1832:               associations = {}
    1833:             elsif associations.length == 1 && (assocs = associations.first).is_a?(Hash) && assocs.length == 1 && (pr_assoc = assocs.to_a.first) && pr_assoc.first.respond_to?(:call)
    1834:               callback, assoc = pr_assoc
    1835:               associations = assoc.is_a?(Array) ? assoc : [assoc]
    1836:             end
    1837:           end
    1838:           ds = if loader.arity == 1
    1839:             loader.call(:self=>ds, :table_alias=>assoc_table_alias, :implicit_qualifier=>ta, :callback=>callback)
    1840:           else
    1841:             loader.call(ds, assoc_table_alias, ta)
    1842:           end
    1843:           ds = ds.order_more(*qualified_expression(r[:order], assoc_table_alias)) if r[:order] and r[:order_eager_graph]
    1844:           eager_graph = ds.opts[:eager_graph]
    1845:           eager_graph[:requirements][assoc_table_alias] = requirements.dup
    1846:           eager_graph[:reflections][assoc_table_alias] = r
    1847:           eager_graph[:cartesian_product_number] += r[:cartesian_product_number] || 2
    1848:           ds = ds.eager_graph_associations(ds, r.associated_class, assoc_table_alias, requirements + [assoc_table_alias], *associations) unless associations.empty?
    1849:           ds
    1850:         end

eager_graph_associations(ds, model, ta, requirements, *associations) click to toggle source

Check the associations are valid for the given model. Call eager_graph_association on each association.

Arguments:

ds | Current dataset
model | Current Model
ta | table_alias used for the parent association
requirements | an array, used as a stack for requirements
*associations | the associations to add to the graph

          # File lib/sequel/model/associations.rb, line 1861
    1861:         def eager_graph_associations(ds, model, ta, requirements, *associations)
    1862:           return ds if associations.empty?
    1863:           associations.flatten.each do |association|
    1864:             ds = case association
    1865:             when Symbol
    1866:               ds.eager_graph_association(ds, model, ta, requirements, check_association(model, association))
    1867:             when Hash
    1868:               association.each do |assoc, assoc_assocs|
    1869:                 ds = ds.eager_graph_association(ds, model, ta, requirements, check_association(model, assoc), assoc_assocs)
    1870:               end
    1871:               ds
    1872:             else raise(Sequel::Error, 'Associations must be in the form of a symbol or hash')
    1873:             end
    1874:           end
    1875:           ds
    1876:         end

eager_graph_build_associations(hashes) click to toggle source

Replace the array of plain hashes with an array of model objects will all eager_graphed associations set in the associations cache for each object.

          # File lib/sequel/model/associations.rb, line 1880
    1880:         def eager_graph_build_associations(hashes)
    1881:           hashes.replace(EagerGraphLoader.new(self).load(hashes))
    1882:         end

### Private Instance Methods

association_filter_expression(op, ref, obj) click to toggle source

Return an expression for filtering by the given association reflection and associated object.

          # File lib/sequel/model/associations.rb, line 1887
    1887:         def association_filter_expression(op, ref, obj)
    1888:           meth = :"#{ref[:type]}_association_filter_expression"
    1889:           send(meth, op, ref, obj) if respond_to?(meth, true)
    1890:         end

association_filter_handle_inversion(op, exp, cols) click to toggle source

Handle inversion for association filters by returning an inverted expression, plus also handling cases where the referenced columns are NULL.

          # File lib/sequel/model/associations.rb, line 1894
    1894:         def association_filter_handle_inversion(op, exp, cols)
    1895:           if op == :'!=' || op == :'NOT IN'
    1896:             if exp == SQL::Constants::FALSE
    1897:               ~exp
    1898:             else
    1899:               ~exp | Sequel::SQL::BooleanExpression.from_value_pairs(cols.zip([]), :OR)
    1900:             end
    1901:           else
    1902:             exp
    1903:           end
    1904:         end

association_filter_key_expression(keys, meths, obj) click to toggle source

Return an expression for making sure that the given keys match the value of the given methods for either the single object given or for any of the objects given if `obj` is an array.

          # File lib/sequel/model/associations.rb, line 1909
    1909:         def association_filter_key_expression(keys, meths, obj)
    1910:           vals = if obj.is_a?(Sequel::Dataset)
    1911:             {(keys.length == 1 ? keys.first : keys)=>obj.select(*meths).exclude(Sequel::SQL::BooleanExpression.from_value_pairs(meths.zip([]), :OR))}
    1912:           else
    1913:             vals = Array(obj).reject{|o| !meths.all?{|m| o.send(m)}}
    1914:             return SQL::Constants::FALSE if vals.empty?
    1915:             if obj.is_a?(Array)
    1916:               if keys.length == 1
    1917:                 meth = meths.first
    1918:                 {keys.first=>vals.map{|o| o.send(meth)}}
    1919:               else
    1920:                 {keys=>vals.map{|o| meths.map{|m| o.send(m)}}}
    1921:               end
    1922:             else
    1923:               keys.zip(meths.map{|k| obj.send(k)})
    1924:             end
    1925:           end
    1926:           SQL::BooleanExpression.from_value_pairs(vals)
    1927:         end

check_association(model, association) click to toggle source

Make sure the association is valid for this model, and return the related AssociationReflection.

          # File lib/sequel/model/associations.rb, line 1930
    1930:         def check_association(model, association)
    1931:           raise(Sequel::UndefinedAssociation, "Invalid association #{association} for #{model.name}") unless reflection = model.association_reflection(association)
    1932:           raise(Sequel::Error, "Eager loading is not allowed for #{model.name} association #{association}") if reflection[:allow_eager] == false
    1933:           reflection
    1934:         end

eager_load(a, eager_assoc=@opts[:eager]) click to toggle source

Eagerly load all specified associations

          # File lib/sequel/model/associations.rb, line 1937
    1937:         def eager_load(a, eager_assoc=@opts[:eager])
    1938:           return if a.empty?
    1939:           # Key is foreign/primary key name symbol
    1940:           # Value is hash with keys being foreign/primary key values (generally integers)
    1941:           #  and values being an array of current model objects with that
    1942:           #  specific foreign/primary key
    1943:           key_hash = {}
    1944:           # Reflections for all associations to eager load
    1945:           reflections = eager_assoc.keys.collect{|assoc| model.association_reflection(assoc) || (raise Sequel::UndefinedAssociation, "Model: #{self}, Association: #{assoc}")}
    1946:
    1947:           # Populate keys to monitor
    1948:           reflections.each{|reflection| key_hash[reflection.eager_loader_key] ||= Hash.new{|h,k| h[k] = []}}
    1949:
    1950:           # Associate each object with every key being monitored
    1951:           a.each do |rec|
    1952:             key_hash.each do |key, id_map|
    1953:               case key
    1954:               when Array
    1955:                 id_map[key.map{|k| rec[k]}] << rec if key.all?{|k| rec[k]}
    1956:               when Symbol
    1957:                 id_map[rec[key]] << rec if rec[key]
    1958:               end
    1959:             end
    1960:           end
    1961:
    1962:           reflections.each do |r|
    1963:             loader = r[:eager_loader]
    1964:             associations = eager_assoc[r[:name]]
    1965:             if associations.respond_to?(:call)
    1966:               eager_block = associations
    1967:               associations = {}
    1968:             elsif associations.is_a?(Hash) && associations.length == 1 && (pr_assoc = associations.to_a.first) && pr_assoc.first.respond_to?(:call)
    1969:               eager_block, associations = pr_assoc
    1970:             end
    1971:             if loader.arity == 1
    1972:               loader.call(:key_hash=>key_hash, :rows=>a, :associations=>associations, :self=>self, :eager_block=>eager_block)
    1973:             else
    1974:               loader.call(key_hash, a, associations)
    1975:             end
    1976:             a.each{|object| object.send(:run_association_callbacks, r, :after_load, object.associations[r[:name]])} unless r[:after_load].empty?
    1977:           end
    1978:         end

graph_each(&block) click to toggle source

Return plain hashes instead of calling the row_proc if eager_graph is being used.

          # File lib/sequel/model/associations.rb, line 1981
    1981:         def graph_each(&block)
    1982:           @opts[:eager_graph] ? fetch_rows(select_sql, &block) : super
    1983:         end

many_to_many_association_filter_expression(op, ref, obj) click to toggle source

Return a subquery expression for filering by a many_to_many association

          # File lib/sequel/model/associations.rb, line 1986
    1986:         def many_to_many_association_filter_expression(op, ref, obj)
    1987:           lpks, lks, rks = ref.values_at(:left_primary_keys, :left_keys, :right_keys)
    1988:           jt = ref.join_table_alias
    1989:           lpks = lpks.first if lpks.length == 1
    1990:           lpks = ref.qualify(model.table_name, lpks)
    1991:           meths = ref.right_primary_keys
    1992:           meths = ref.qualify(obj.model.table_name, meths) if obj.is_a?(Sequel::Dataset)
    1993:           exp = association_filter_key_expression(ref.qualify(jt, rks), meths, obj)
    1994:           if exp == SQL::Constants::FALSE
    1995:             association_filter_handle_inversion(op, exp, Array(lpks))
    1996:           else
    1997:             association_filter_handle_inversion(op, SQL::BooleanExpression.from_value_pairs(lpks=>model.db.from(ref[:join_table]).select(*ref.qualify(jt, lks)).where(exp).exclude(SQL::BooleanExpression.from_value_pairs(ref.qualify(jt, lks).zip([]), :OR))), Array(lpks))
    1998:           end
    1999:         end

many_to_one_association_filter_expression(op, ref, obj) click to toggle source

Return a simple equality expression for filering by a many_to_one association

          # File lib/sequel/model/associations.rb, line 2002
    2002:         def many_to_one_association_filter_expression(op, ref, obj)
    2003:           keys = ref.qualify(model.table_name, ref[:keys])
    2004:           meths = ref.primary_keys
    2005:           meths = ref.qualify(obj.model.table_name, meths) if obj.is_a?(Sequel::Dataset)
    2006:           association_filter_handle_inversion(op, association_filter_key_expression(keys, meths, obj), keys)
    2007:         end

one_to_many_association_filter_expression(op, ref, obj) click to toggle source

Return a simple equality expression for filering by a one_to_* association

          # File lib/sequel/model/associations.rb, line 2010
    2010:         def one_to_many_association_filter_expression(op, ref, obj)
    2011:           keys = ref.qualify(model.table_name, ref[:primary_keys])
    2012:           meths = ref[:keys]
    2013:           meths = ref.qualify(obj.model.table_name, meths) if obj.is_a?(Sequel::Dataset)
    2014:           association_filter_handle_inversion(op, association_filter_key_expression(keys, meths, obj), keys)
    2015:         end

Also aliased as: one_to_one_association_filter_expression
one_to_one_association_filter_expression(op, ref, obj) click to toggle source
Alias for: one_to_many_association_filter_expression
post_load(all_records) click to toggle source

Build associations from the graph if # was used, and/or load other associations if # was used.

          # File lib/sequel/model/associations.rb, line 2020
    2020:         def post_load(all_records)
    2021:           eager_graph_build_associations(all_records) if @opts[:eager_graph]
    2022:           eager_load(all_records) if @opts[:eager]
    2023:           super
    2024:         end

Disabled; run with --debug to generate this.

[Validate]

Generated with the Darkfish Rdoc Generator 1.1.6.