### Home Classes Methods

### In Files

- lib/sequel/model/associations.rb

### Methods

- #all_association_reflections
- #apply_association_dataset_opts
- #apply_correlated_subquery_eager_limit_strategy
- #apply_window_function_eager_limit_strategy
- #associate
- #association_module
- #association_module_def
- #association_module_private_def
- #association_reflection
- #associations
- #def_add_method
- #def_association_dataset_methods
- #def_many_to_many
- #def_many_to_one
- #def_one_to_many
- #def_one_to_one
- #def_remove_methods
- #eager_graph_dataset
- #eager_loading_dataset
- #inherited
- #many_to_many
- #many_to_one
- #one_to_many
- #one_to_one

### 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::ClassMethods

Each kind of association adds a number of instance methods to the model class which are specialized according to the association type and optional parameters given in the definition. Example:

      class Project < Sequel::Model
        many_to_one :portfolio
        # or: one_to_one :portfolio
        one_to_many :milestones
        # or: many_to_many :milestones
      end

The project class now has the following instance methods:

portfolio | Returns the associated portfolio.
portfolio=(obj) | Sets the associated portfolio to the object, but the change is not persisted until you save the record (for many_to_one associations).
portfolio_dataset | Returns a dataset that would return the associated portfolio, only useful in fairly specific circumstances.
milestones | Returns an array of associated milestones
add_milestone(obj) | Associates the passed milestone with this object.
remove_milestone(obj) | Removes the association with the passed milestone.
remove_all_milestones | Removes associations with all associated milestones.
milestones_dataset | Returns a dataset that would return the associated milestones, allowing for further filtering/limiting/etc.

If you want to override the behavior of the add_/remove_/remove_all_/ methods or the association setter method, there are private instance methods created that are prepended with an underscore (e.g. _add_milestone or _portfolio=). The private instance methods can be easily overridden, but you shouldn’t override the public instance methods without calling super, as they deal with callbacks and caching.

By default the classes for the associations are inferred from the association name, so for example the Project#portfolio will return an instance of Portfolio, and Project#milestones will return an array of Milestone instances. You can use the :class option to change which class is used.

Association definitions are also reflected by the class, e.g.:

      Project.associations
      => [:portfolio, :milestones]
      Project.association_reflection(:portfolio)
      => {:type => :many_to_one, :name => :portfolio, ...}

Associations should not have the same names as any of the columns in the model’s current table they reference. If you are dealing with an existing schema that has a column named status, you can’t name the association status, you’d have to name it foo_status or something else. If you give an association the same name as a column, you will probably end up with an association that doesn’t work, or a SystemStackError.

For a more in depth general overview, as well as a reference guide, see the Association Basics guide. For examples of advanced usage, see the Advanced Associations guide.

### Attributes

association_reflections[R]

All association reflections defined for this model (default: {}).

default_eager_limit_strategy[RW]

The default :eager_limit_strategy option to use for *_many associations (default: nil)

### Public Instance Methods

all_association_reflections() click to toggle source

Array of all association reflections for this model class

         # File lib/sequel/model/associations.rb, line 639
    639:         def all_association_reflections
    640:           association_reflections.values
    641:         end

apply_association_dataset_opts(opts, ds) click to toggle source

Given an association reflection and a dataset, apply the :select, :conditions, :order, :eager, :distinct, and :eager_block association options to the given dataset and return the dataset or a modified copy of it.

         # File lib/sequel/model/associations.rb, line 647
    647:         def apply_association_dataset_opts(opts, ds)
    648:           ds = ds.select(*opts.select) if opts.select
    649:           if c = opts[:conditions]
    650:             ds = (c.is_a?(Array) && !Sequel.condition_specifier?(c)) ? ds.filter(*c) : ds.filter(c)
    651:           end
    652:           ds = ds.order(*opts[:order]) if opts[:order]
    653:           ds = ds.eager(opts[:eager]) if opts[:eager]
    654:           ds = ds.distinct if opts[:distinct]
    655:           ds = opts[:eager_block].call(ds) if opts[:eager_block]
    656:           ds
    657:         end

associate(type, name, opts = {}, &block) click to toggle source

Associates a related model with the current model. The following types are supported:

:many_to_one | Foreign key in current model’s table points to associated model’s primary key. Each associated model object can be associated with more than one current model objects. Each current model object can be associated with only one associated model object.
:one_to_many | Foreign key in associated model’s table points to this model’s primary key. Each current model object can be associated with more than one associated model objects. Each associated model object can be associated with only one current model object.
:one_to_one | Similar to one_to_many in terms of foreign keys, but only one object is associated to the current object through the association. The methods created are similar to many_to_one, except that the one_to_one setter method saves the passed object.
:many_to_many | A join table is used that has a foreign key that points to this model’s primary key and a foreign key that points to the associated model’s primary key. Each current model object can be associated with many associated model objects, and each associated model object can be associated with many current model objects.

The following options can be supplied:

### All Types

:after_add | Symbol, Proc, or array of both/either specifying a callback to call after a new item is added to the association.
:after_load | Symbol, Proc, or array of both/either specifying a callback to call after the associated record(s) have been retrieved from the database.
:after_remove | Symbol, Proc, or array of both/either specifying a callback to call after an item is removed from the association.
:after_set | Symbol, Proc, or array of both/either specifying a callback to call after an item is set using the association setter method.
:allow_eager | If set to false, you cannot load the association eagerly via eager or eager_graph
:before_add | Symbol, Proc, or array of both/either specifying a callback to call before a new item is added to the association.
:before_remove | Symbol, Proc, or array of both/either specifying a callback to call before an item is removed from the association.
:before_set | Symbol, Proc, or array of both/either specifying a callback to call before an item is set using the association setter method.
:cartesian_product_number | the number of joins completed by this association that could cause more than one row for each row in the current table (default: 0 for many_to_one and one_to_one associations, 1 for one_to_many and many_to_many associations).
:class | The associated class or its name. If not given, uses the association’s name, which is camelized (and singularized unless the type is :many_to_one or :one_to_one)
:clone | Merge the current options and block into the options and block used in defining the given association. Can be used to DRY up a bunch of similar associations that all share the same options such as :class and :key, while changing the order and block used.
:conditions | The conditions to use to filter the association, can be any argument passed to filter.
:dataset | A proc that is instance_evaled to get the base dataset to use for the _dataset method (before the other options are applied).
:distinct | Use the DISTINCT clause when selecting associating object, both when lazy loading and eager loading via .eager (but not when using .eager_graph).
:eager | The associations to eagerly load via `eager` when loading the associated object(s).
:eager_block | If given, use the block instead of the default block when eagerly loading. To not use a block when eager loading (when one is used normally), set to nil.
:eager_graph | The associations to eagerly load via `eager_graph` when loading the associated object(s). many_to_many associations with this option cannot be eagerly loaded via `eager`.
:eager_grapher | A proc to use to implement eager loading via `eager_graph`, overriding the default. Takes one or three arguments. If three arguments, they are a dataset, an alias to use for the table to graph for this association, and the alias that was used for the current table (since you can cascade associations). If one argument, is passed a hash with keys :self, :table_alias, and :implicit_qualifier, corresponding to the three arguments, and an optional additional key :eager_block, a callback accepting one argument, the associated dataset. This is used to customize the association at query time. Should return a copy of the dataset with the association graphed into it.
:eager_limit_strategy | Determines the strategy used for enforcing limits when eager loading associations via the `eager` method. For one_to_one associations, no strategy is used by default, and for *_many associations, the :ruby strategy is used by default, which still retrieves all records but slices the resulting array after the association is retrieved. You can pass a `true` value for this option to have Sequel pick what it thinks is the best choice for the database, or specify a specific symbol to manually select a strategy. one_to_one associations support :distinct_on, :window_function, and :correlated_subquery. *_many associations support :ruby, :window_function, and :correlated_subquery.
:eager_loader | A proc to use to implement eager loading, overriding the default. Takes one or three arguments. If three arguments, the first should be a key hash (used solely to enhance performance), the second an array of records, and the third a hash of dependent associations. If one argument, is passed a hash with keys :key_hash, :rows, and :associations, corresponding to the three arguments, and an additional key :self, which is the dataset doing the eager loading. In the proc, the associated records should be queried from the database and the associations cache for each record should be populated.
:eager_loader_key | A symbol for the key column to use to populate the key hash for the eager loader.
:extend | A module or array of modules to extend the dataset with.
:graph_alias_base | The base name to use for the table alias when eager graphing. Defaults to the name of the association. If the alias name has already been used in the query, Sequel will create a unique alias by appending a numeric suffix (e.g. alias_0, alias_1, …) until the alias is unique.
:graph_block | The block to pass to join_table when eagerly loading the association via `eager_graph`.
:graph_conditions | The additional conditions to use on the SQL join when eagerly loading the association via `eager_graph`. Should be a hash or an array of two element arrays. If not specified, the :conditions option is used if it is a hash or array of two element arrays.
:graph_join_type | The type of SQL join to use when eagerly loading the association via eager_graph. Defaults to :left_outer.
:graph_only_conditions | The conditions to use on the SQL join when eagerly loading the association via `eager_graph`, instead of the default conditions specified by the foreign/primary keys. This option causes the :graph_conditions option to be ignored.
:graph_select | A column or array of columns to select from the associated table when eagerly loading the association via `eager_graph`. Defaults to all columns in the associated table.
:limit | Limit the number of records to the provided value. Use an array with two elements for the value to specify a limit (first element) and an offset (second element).
:methods_module | The module that methods the association creates will be placed into. Defaults to the module containing the model’s columns.
:order | the column(s) by which to order the association dataset. Can be a singular column symbol or an array of column symbols.
:order_eager_graph | Whether to add the association’s order to the graphed dataset’s order when graphing via `eager_graph`. Defaults to true, so set to false to disable.
:read_only | Do not add a setter method (for many_to_one or one_to_one associations), or add_/remove_/remove_all_ methods (for one_to_many and many_to_many associations).
:reciprocal | the symbol name of the reciprocal association, if it exists. By default, Sequel will try to determine it by looking at the associated model’s assocations for a association that matches the current association’s key(s). Set to nil to not use a reciprocal.
:select | the columns to select. Defaults to the associated class’s table_name.* in a many_to_many association, which means it doesn’t include the attributes from the join table. If you want to include the join table attributes, you can use this option, but beware that the join table attributes can clash with attributes from the model table, so you should alias any attributes that have the same name in both the join table and the associated table.
:validate | Set to false to not validate when implicitly saving any associated object.

### :many_to_one

:key | foreign key in current model’s table that references associated model’s primary key, as a symbol. Defaults to :”#{name}_id”. Can use an array of symbols for a composite key association.
:key_column | Similar to, and usually identical to, :key, but :key refers to the model method to call, where :key_column refers to the underlying column. Should only be used if the the model method differs from the foreign key column, in conjunction with defining a model alias method for the key column.
:primary_key | column in the associated table that :key option references, as a symbol. Defaults to the primary key of the associated table. Can use an array of symbols for a composite key association.
:primary_key_method | the method symbol or array of method symbols to call on the associated object to get the foreign key values. Defaults to :primary_key option.
:qualify | Whether to use qualifier primary keys when loading the association. The default is true, so you must set to false to not qualify. Qualification rarely causes problems, but it’s necessary to disable in some cases, such as when you are doing a JOIN USING operation on the column on Oracle.

### :one_to_many and :one_to_one

:key | foreign key in associated model’s table that references current model’s primary key, as a symbol. Defaults to :”#{self.name.underscore}_id”. Can use an array of symbols for a composite key association.
:key_method | the method symbol or array of method symbols to call on the associated object to get the foreign key values. Defaults to :key option.
:primary_key | column in the current table that :key option references, as a symbol. Defaults to primary key of the current table. Can use an array of symbols for a composite key association.
:primary_key_column | Similar to, and usually identical to, :primary_key, but :primary_key refers to the model method call, where :primary_key_column refers to the underlying column. Should only be used if the the model method differs from the primary key column, in conjunction with defining a model alias method for the primary key column.

### :many_to_many

:graph_join_table_block | The block to pass to `join_table` for the join table when eagerly loading the association via `eager_graph`.
:graph_join_table_conditions | The additional conditions to use on the SQL join for the join table when eagerly loading the association via `eager_graph`. Should be a hash or an array of two element arrays.
:graph_join_table_join_type | The type of SQL join to use for the join table when eagerly loading the association via `eager_graph`. Defaults to the :graph_join_type option or :left_outer.
:graph_join_table_only_conditions | The conditions to use on the SQL join for the join table when eagerly loading the association via `eager_graph`, instead of the default conditions specified by the foreign/primary keys. This option causes the :graph_join_table_conditions option to be ignored.
:join_table | name of table that includes the foreign keys to both the current model and the associated model, as a symbol. Defaults to the name of current model and name of associated model, pluralized, underscored, sorted, and joined with ‘_’.
:join_table_block | proc that can be used to modify the dataset used in the add/remove/remove_all methods. Should accept a dataset argument and return a modified dataset if present.
:left_key | foreign key in join table that points to current model’s primary key, as a symbol. Defaults to :”#{self.name.underscore}_id”. Can use an array of symbols for a composite key association.
:left_primary_key | column in current table that :left_key points to, as a symbol. Defaults to primary key of current table. Can use an array of symbols for a composite key association.
:left_primary_key_column | Similar to, and usually identical to, :left_primary_key, but :left_primary_key refers to the model method to call, where :left_primary_key_column refers to the underlying column. Should only be used if the model method differs from the left primary key column, in conjunction with defining a model alias method for the left primary key column.
:right_key | foreign key in join table that points to associated model’s primary key, as a symbol. Defaults to :”#{name.to_s.singularize}_id”. Can use an array of symbols for a composite key association.
:right_primary_key | column in associated table that :right_key points to, as a symbol. Defaults to primary key of the associated table. Can use an array of symbols for a composite key association.
:right_primary_key_method | the method symbol or array of method symbols to call on the associated object to get the foreign key values for the join table. Defaults to :right_primary_key option.
:uniq | Adds a after_load callback that makes the array of objects unique.

         # File lib/sequel/model/associations.rb, line 855
    855:         def associate(type, name, opts = {}, &block)
    856:           raise(Error, 'one_to_many association type with :one_to_one option removed, used one_to_one association type') if opts[:one_to_one] && type == :one_to_many
    857:           raise(Error, 'invalid association type') unless assoc_class = ASSOCIATION_TYPES[type]
    858:           raise(Error, 'Model.associate name argument must be a symbol') unless Symbol === name
    859:           raise(Error, ':eager_loader option must have an arity of 1 or 3') if opts[:eager_loader] && ![1, 3].include?(opts[:eager_loader].arity)
    860:           raise(Error, ':eager_grapher option must have an arity of 1 or 3') if opts[:eager_grapher] && ![1, 3].include?(opts[:eager_grapher].arity)
    861:
    862:           # dup early so we don't modify opts
    863:           orig_opts = opts.dup
    864:           orig_opts = association_reflection(opts[:clone])[:orig_opts].merge(orig_opts) if opts[:clone]
    865:           opts = orig_opts.merge(:type => type, :name => name, :cache => true, :model => self)
    866:           opts[:block] = block if block
    867:           opts = assoc_class.new.merge!(opts)
    868:           opts[:eager_block] = block unless opts.include?(:eager_block)
    869:           opts[:graph_join_type] ||= :left_outer
    870:           opts[:order_eager_graph] = true unless opts.include?(:order_eager_graph)
    871:           conds = opts[:conditions]
    872:           opts[:graph_alias_base] ||= name
    873:           opts[:graph_conditions] = conds if !opts.include?(:graph_conditions) and Sequel.condition_specifier?(conds)
    874:           opts[:graph_conditions] = opts.fetch(:graph_conditions, []).to_a
    875:           opts[:graph_select] = Array(opts[:graph_select]) if opts[:graph_select]
    876:           [:before_add, :before_remove, :after_add, :after_remove, :after_load, :before_set, :after_set, :extend].each do |cb_type|
    877:             opts[cb_type] = Array(opts[cb_type])
    878:           end
    879:           late_binding_class_option(opts, opts.returns_array? ? singularize(name) : name)
    880:
    881:           send(:"def_#{type}", opts)
    882:
    883:           orig_opts.delete(:clone)
    884:           orig_opts.merge!(:class_name=>opts[:class_name], :class=>opts[:class], :block=>block)
    885:           opts[:orig_opts] = orig_opts
    886:           # don't add to association_reflections until we are sure there are no errors
    887:           association_reflections[name] = opts
    888:         end

association_reflection(name) click to toggle source

The association reflection hash for the association of the given name.

         # File lib/sequel/model/associations.rb, line 891
    891:         def association_reflection(name)
    892:           association_reflections[name]
    893:         end

associations() click to toggle source

Array of association name symbols

         # File lib/sequel/model/associations.rb, line 896
    896:         def associations
    897:           association_reflections.keys
    898:         end

eager_loading_dataset(opts, ds, select, associations, eager_options={}) click to toggle source

Modify and return eager loading dataset based on association options.

         # File lib/sequel/model/associations.rb, line 901
    901:         def eager_loading_dataset(opts, ds, select, associations, eager_options={})
    902:           ds = apply_association_dataset_opts(opts, ds)
    903:           ds = ds.select(*select) if select
    904:           if opts[:eager_graph]
    905:             raise(Error, "cannot eagerly load a #{opts[:type]} association that uses :eager_graph") if opts.eager_loading_use_associated_key?
    906:             ds = ds.eager_graph(opts[:eager_graph])
    907:           end
    908:           ds = ds.eager(associations) unless Array(associations).empty?
    909:           ds = eager_options[:eager_block].call(ds) if eager_options[:eager_block]
    910:           if opts.eager_loading_use_associated_key?
    911:             ds = if opts[:uses_left_composite_keys]
    912:               ds.select_append(*opts.associated_key_alias.zip(opts.eager_loading_predicate_key).map{|a, k| SQL::AliasedExpression.new(k, a)})
    913:             else
    914:               ds.select_append(SQL::AliasedExpression.new(opts.eager_loading_predicate_key, opts.associated_key_alias))
    915:             end
    916:           end
    917:           ds
    918:         end

inherited(subclass) click to toggle source

Copy the association reflections to the subclass

         # File lib/sequel/model/associations.rb, line 921
    921:         def inherited(subclass)
    922:           super
    923:           subclass.instance_variable_set(:@association_reflections, association_reflections.dup)
    924:           subclass.default_eager_limit_strategy =  default_eager_limit_strategy
    925:         end

many_to_many(name, opts={}, &block) click to toggle source

Shortcut for adding a many_to_many association, see #

         # File lib/sequel/model/associations.rb, line 928
    928:         def many_to_many(name, opts={}, &block)
    929:           associate(:many_to_many, name, opts, &block)
    930:         end

many_to_one(name, opts={}, &block) click to toggle source

Shortcut for adding a many_to_one association, see #

         # File lib/sequel/model/associations.rb, line 933
    933:         def many_to_one(name, opts={}, &block)
    934:           associate(:many_to_one, name, opts, &block)
    935:         end

one_to_many(name, opts={}, &block) click to toggle source

Shortcut for adding a one_to_many association, see #

         # File lib/sequel/model/associations.rb, line 938
    938:         def one_to_many(name, opts={}, &block)
    939:           associate(:one_to_many, name, opts, &block)
    940:         end

one_to_one(name, opts={}, &block) click to toggle source

Shortcut for adding a one_to_one association, see #.

         # File lib/sequel/model/associations.rb, line 943
    943:         def one_to_one(name, opts={}, &block)
    944:           associate(:one_to_one, name, opts, &block)
    945:         end

### Private Instance Methods

apply_correlated_subquery_eager_limit_strategy(ds, opts) click to toggle source

Use a correlated subquery to limit the results of the eager loading dataset.

         # File lib/sequel/model/associations.rb, line 950
    950:         def apply_correlated_subquery_eager_limit_strategy(ds, opts)
    951:           klass = opts.associated_class
    952:           kds = klass.dataset
    953:           dsa = ds.send(:dataset_alias, 1)
    954:           raise Error, "can't use a correlated subquery if the associated class (#{opts.associated_class.inspect}) does not have a primary key" unless pk = klass.primary_key
    955:           pka = Array(pk)
    956:           raise Error, "can't use a correlated subquery if the associated class (#{opts.associated_class.inspect}) has a composite primary key and the database does not support multiple column IN" if pka.length > 1 && !ds.supports_multiple_column_in?
    957:           table = kds.opts[:from]
    958:           raise Error, "can't use a correlated subquery unless the associated class (#{opts.associated_class.inspect}) uses a single FROM table" unless table && table.length == 1
    959:           table = table.first
    960:           if order = ds.opts[:order]
    961:             oproc = lambda do |x|
    962:               case x
    963:               when Symbol
    964:                 t, c, a = ds.send(:split_symbol, x)
    965:                 if t && t.to_sym == table
    966:                   SQL::QualifiedIdentifier.new(dsa, c)
    967:                 else
    968:                   x
    969:                 end
    970:               when SQL::QualifiedIdentifier
    971:                 if x.table == table
    972:                   SQL::QualifiedIdentifier.new(dsa, x.column)
    973:                 else
    974:                   x
    975:                 end
    976:               when SQL::OrderedExpression
    977:                 SQL::OrderedExpression.new(oproc.call(x.expression), x.descending, :nulls=>x.nulls)
    978:               else
    979:                 x
    980:               end
    981:             end
    982:             order = order.map(&oproc)
    983:           end
    984:           limit, offset = opts.limit_and_offset
    985:
    986:           subquery = yield kds.
    987:             unlimited.
    988:             from(SQL::AliasedExpression.new(table, dsa)).
    989:             select(*pka.map{|k| SQL::QualifiedIdentifier.new(dsa, k)}).
    990:             order(*order).
    991:             limit(limit, offset)
    992:
    993:           pk = if pk.is_a?(Array)
    994:             pk.map{|k| SQL::QualifiedIdentifier.new(table, k)}
    995:           else
    996:             SQL::QualifiedIdentifier.new(table, pk)
    997:           end
    998:           ds.filter(pk=>subquery)
    999:         end

apply_window_function_eager_limit_strategy(ds, opts) click to toggle source

Use a window function to limit the results of the eager loading dataset.

          # File lib/sequel/model/associations.rb, line 1002
    1002:         def apply_window_function_eager_limit_strategy(ds, opts)
    1003:           rn = ds.row_number_column
    1004:           limit, offset = opts.limit_and_offset
    1005:           ds = ds.unordered.select_append{row_number(:over, :partition=>opts.eager_loading_predicate_key, :order=>ds.opts[:order]){}.as(rn)}.from_self
    1006:           ds = if opts[:type] == :one_to_one
    1007:             ds.where(rn => 1)
    1008:           elsif offset
    1009:             offset += 1
    1010:             ds.where(rn => (offset...(offset+limit)))
    1011:           else
    1012:             ds.where{SQL::Identifier.new(rn) <= limit}
    1013:           end
    1014:         end

association_module(opts={}) click to toggle source

The module to use for the association’s methods. Defaults to the overridable_methods_module.

          # File lib/sequel/model/associations.rb, line 1018
    1018:         def association_module(opts={})
    1019:           opts.fetch(:methods_module, overridable_methods_module)
    1020:         end

association_module_def(name, opts={}, &block) click to toggle source

Add a method to the module included in the class, so the method can be easily overridden in the class itself while allowing for super to be called.

          # File lib/sequel/model/associations.rb, line 1025
    1025:         def association_module_def(name, opts={}, &block)
    1026:           association_module(opts).module_eval{define_method(name, &block)}
    1027:         end

association_module_private_def(name, opts={}, &block) click to toggle source

Add a private method to the module included in the class.

          # File lib/sequel/model/associations.rb, line 1030
    1030:         def association_module_private_def(name, opts={}, &block)
    1031:           association_module_def(name, opts, &block)
    1032:           association_module(opts).send(:private, name)
    1033:         end

def_add_method(opts) click to toggle source

Add the add_ instance method

          # File lib/sequel/model/associations.rb, line 1036
    1036:         def def_add_method(opts)
    1037:           association_module_def(opts.add_method, opts){|o,*args| add_associated_object(opts, o, *args)}
    1038:         end

def_association_dataset_methods(opts) click to toggle source

Adds the association dataset methods to the association methods module.

          # File lib/sequel/model/associations.rb, line 1041
    1041:         def def_association_dataset_methods(opts)
    1042:           # If a block is given, define a helper method for it, because it takes
    1043:           # an argument.  This is unnecessary in Ruby 1.9, as that has instance_exec.
    1044:           association_module_private_def(opts.dataset_helper_method, opts, &opts[:block]) if opts[:block]
    1045:           association_module_private_def(opts._dataset_method, opts, &opts[:dataset])
    1046:           association_module_def(opts.dataset_method, opts){_dataset(opts)}
    1047:           def_association_method(opts)
    1048:         end

def_many_to_many(opts) click to toggle source

Configures many_to_many association reflection and adds the related association methods

          # File lib/sequel/model/associations.rb, line 1067
    1067:         def def_many_to_many(opts)
    1068:           name = opts[:name]
    1069:           model = self
    1070:           left = (opts[:left_key] ||= opts.default_left_key)
    1071:           lcks = opts[:left_keys] = Array(left)
    1072:           right = (opts[:right_key] ||= opts.default_right_key)
    1073:           rcks = opts[:right_keys] = Array(right)
    1074:           left_pk = (opts[:left_primary_key] ||= self.primary_key)
    1075:           lcpks = opts[:left_primary_keys] = Array(left_pk)
    1076:           lpkc = opts[:left_primary_key_column] ||= left_pk
    1077:           lpkcs = opts[:left_primary_key_columns] ||= Array(lpkc)
    1078:           elk = opts.eager_loader_key
    1079:           raise(Error, "mismatched number of left composite keys: #{lcks.inspect} vs #{lcpks.inspect}") unless lcks.length == lcpks.length
    1080:           if opts[:right_primary_key]
    1081:             rcpks = Array(opts[:right_primary_key])
    1082:             raise(Error, "mismatched number of right composite keys: #{rcks.inspect} vs #{rcpks.inspect}") unless rcks.length == rcpks.length
    1083:           end
    1084:           uses_lcks = opts[:uses_left_composite_keys] = lcks.length > 1
    1085:           uses_rcks = opts[:uses_right_composite_keys] = rcks.length > 1
    1086:           opts[:cartesian_product_number] ||= 1
    1087:           join_table = (opts[:join_table] ||= opts.default_join_table)
    1088:           left_key_alias = opts[:left_key_alias] ||= opts.default_associated_key_alias
    1089:           graph_jt_conds = opts[:graph_join_table_conditions] = opts.fetch(:graph_join_table_conditions, []).to_a
    1090:           opts[:graph_join_table_join_type] ||= opts[:graph_join_type]
    1091:           opts[:after_load].unshift(:array_uniq!) if opts[:uniq]
    1092:           opts[:dataset] ||= proc{opts.associated_class.inner_join(join_table, rcks.zip(opts.right_primary_keys) + lcks.zip(lcpks.map{|k| send(k)}))}
    1093:
    1094:           opts[:eager_loader] ||= proc do |eo|
    1095:             h = eo[:key_hash][elk]
    1096:             rows = eo[:rows]
    1097:             rows.each{|object| object.associations[name] = []}
    1098:             r = rcks.zip(opts.right_primary_keys)
    1099:             l = [[opts.qualify(opts.join_table_alias, left), h.keys]]
    1100:             ds = model.eager_loading_dataset(opts, opts.associated_class.inner_join(join_table, r + l), nil, eo[:associations], eo)
    1101:             case opts.eager_limit_strategy
    1102:             when :window_function
    1103:               delete_rn = true
    1104:               rn = ds.row_number_column
    1105:               ds = apply_window_function_eager_limit_strategy(ds, opts)
    1106:             when :correlated_subquery
    1107:               ds = apply_correlated_subquery_eager_limit_strategy(ds, opts) do |xds|
    1108:                 dsa = ds.send(:dataset_alias, 2)
    1109:                 xds.inner_join(join_table, r + lcks.map{|k| [k, SQL::QualifiedIdentifier.new(opts.join_table_alias, k)]}, :table_alias=>dsa)
    1110:               end
    1111:             end
    1112:             ds.all do |assoc_record|
    1113:               assoc_record.values.delete(rn) if delete_rn
    1114:               hash_key = if uses_lcks
    1115:                 left_key_alias.map{|k| assoc_record.values.delete(k)}
    1116:               else
    1117:                 assoc_record.values.delete(left_key_alias)
    1118:               end
    1119:               next unless objects = h[hash_key]
    1120:               objects.each{|object| object.associations[name].push(assoc_record)}
    1121:             end
    1122:             if opts.eager_limit_strategy == :ruby
    1123:               limit, offset = opts.limit_and_offset
    1124:               rows.each{|o| o.associations[name] = o.associations[name].slice(offset||0, limit) || []}
    1125:             end
    1126:           end
    1127:
    1128:           join_type = opts[:graph_join_type]
    1129:           select = opts[:graph_select]
    1130:           use_only_conditions = opts.include?(:graph_only_conditions)
    1131:           only_conditions = opts[:graph_only_conditions]
    1132:           conditions = opts[:graph_conditions]
    1133:           graph_block = opts[:graph_block]
    1134:           use_jt_only_conditions = opts.include?(:graph_join_table_only_conditions)
    1135:           jt_only_conditions = opts[:graph_join_table_only_conditions]
    1136:           jt_join_type = opts[:graph_join_table_join_type]
    1137:           jt_graph_block = opts[:graph_join_table_block]
    1138:           opts[:eager_grapher] ||= proc do |eo|
    1139:             ds = eo[:self]
    1140:             ds = ds.graph(join_table, use_jt_only_conditions ? jt_only_conditions : lcks.zip(lpkcs) + graph_jt_conds, :select=>false, :table_alias=>ds.unused_table_alias(join_table, [eo[:table_alias]]), :join_type=>jt_join_type, :implicit_qualifier=>eo[:implicit_qualifier], :from_self_alias=>ds.opts[:eager_graph][:master], &jt_graph_block)
    1141:             ds.graph(eager_graph_dataset(opts, eo), use_only_conditions ? only_conditions : opts.right_primary_keys.zip(rcks) + conditions, :select=>select, :table_alias=>eo[:table_alias], :join_type=>join_type, &graph_block)
    1142:           end
    1143:
    1144:           def_association_dataset_methods(opts)
    1145:
    1146:           return if opts[:read_only]
    1147:
    1148:           association_module_private_def(opts._add_method, opts) do |o|
    1149:             h = {}
    1150:             lcks.zip(lcpks).each{|k, pk| h[k] = send(pk)}
    1151:             rcks.zip(opts.right_primary_key_methods).each{|k, pk| h[k] = o.send(pk)}
    1152:             _join_table_dataset(opts).insert(h)
    1153:           end
    1154:           association_module_private_def(opts._remove_method, opts) do |o|
    1155:             _join_table_dataset(opts).filter(lcks.zip(lcpks.map{|k| send(k)}) + rcks.zip(opts.right_primary_key_methods.map{|k| o.send(k)})).delete
    1156:           end
    1157:           association_module_private_def(opts._remove_all_method, opts) do
    1158:             _join_table_dataset(opts).filter(lcks.zip(lcpks.map{|k| send(k)})).delete
    1159:           end
    1160:
    1161:           def_add_method(opts)
    1162:           def_remove_methods(opts)
    1163:         end

def_many_to_one(opts) click to toggle source

Configures many_to_one association reflection and adds the related association methods

          # File lib/sequel/model/associations.rb, line 1166
    1166:         def def_many_to_one(opts)
    1167:           name = opts[:name]
    1168:           model = self
    1169:           opts[:key] = opts.default_key unless opts.include?(:key)
    1170:           key_column = key = opts[:key]
    1171:           cks = opts[:graph_keys] = opts[:keys] = Array(key)
    1172:           if opts[:key_column]
    1173:             key_column = opts[:key_column]
    1174:             opts[:eager_loader_key] ||= key_column
    1175:             opts[:graph_keys] = Array(key_column)
    1176:           end
    1177:           opts[:qualified_key] = opts.qualify_cur(key)
    1178:           if opts[:primary_key]
    1179:             cpks = Array(opts[:primary_key])
    1180:             raise(Error, "mismatched number of composite keys: #{cks.inspect} vs #{cpks.inspect}") unless cks.length == cpks.length
    1181:           end
    1182:           uses_cks = opts[:uses_composite_keys] = cks.length > 1
    1183:           qualify = opts[:qualify] != false
    1184:           opts[:cartesian_product_number] ||= 0
    1185:           opts[:dataset] ||= proc do
    1186:             klass = opts.associated_class
    1187:             klass.filter(Array(opts.qualified_primary_key).zip(cks.map{|k| send(k)}))
    1188:           end
    1189:           opts[:eager_loader] ||= proc do |eo|
    1190:             h = eo[:key_hash][key_column]
    1191:             keys = h.keys
    1192:             # Default the cached association to nil, so any object that doesn't have it
    1193:             # populated will have cached the negative lookup.
    1194:             eo[:rows].each{|object| object.associations[name] = nil}
    1195:             # Skip eager loading if no objects have a foreign key for this association
    1196:             unless keys.empty?
    1197:               klass = opts.associated_class
    1198:               model.eager_loading_dataset(opts, klass.filter(opts.qualified_primary_key=>keys), nil, eo[:associations], eo).all do |assoc_record|
    1199:                 hash_key = uses_cks ? opts.primary_key_methods.map{|k| assoc_record.send(k)} : assoc_record.send(opts.primary_key_method)
    1200:                 next unless objects = h[hash_key]
    1201:                 objects.each{|object| object.associations[name] = assoc_record}
    1202:               end
    1203:             end
    1204:           end
    1205:
    1206:           join_type = opts[:graph_join_type]
    1207:           select = opts[:graph_select]
    1208:           use_only_conditions = opts.include?(:graph_only_conditions)
    1209:           only_conditions = opts[:graph_only_conditions]
    1210:           conditions = opts[:graph_conditions]
    1211:           graph_block = opts[:graph_block]
    1212:           graph_cks = opts[:graph_keys]
    1213:           opts[:eager_grapher] ||= proc do |eo|
    1214:             ds = eo[:self]
    1215:             ds.graph(eager_graph_dataset(opts, eo), use_only_conditions ? only_conditions : opts.primary_keys.zip(graph_cks) + conditions, eo.merge(:select=>select, :join_type=>join_type, :from_self_alias=>ds.opts[:eager_graph][:master]), &graph_block)
    1216:           end
    1217:
    1218:           def_association_dataset_methods(opts)
    1219:
    1220:           return if opts[:read_only]
    1221:
    1222:           association_module_private_def(opts._setter_method, opts){|o| cks.zip(opts.primary_key_methods).each{|k, pk| send(:"#{k}=", (o.send(pk) if o))}}
    1223:           association_module_def(opts.setter_method, opts){|o| set_associated_object(opts, o)}
    1224:         end

def_one_to_many(opts) click to toggle source

Configures one_to_many and one_to_one association reflections and adds the related association methods

          # File lib/sequel/model/associations.rb, line 1227
    1227:         def def_one_to_many(opts)
    1228:           one_to_one = opts[:type] == :one_to_one
    1229:           name = opts[:name]
    1230:           model = self
    1231:           key = (opts[:key] ||= opts.default_key)
    1232:           km = opts[:key_method] ||= opts[:key]
    1233:           cks = opts[:keys] = Array(key)
    1234:           primary_key = (opts[:primary_key] ||= self.primary_key)
    1235:           cpks = opts[:primary_keys] = Array(primary_key)
    1236:           pkc = opts[:primary_key_column] ||= primary_key
    1237:           pkcs = opts[:primary_key_columns] ||= Array(pkc)
    1238:           elk = opts.eager_loader_key
    1239:           raise(Error, "mismatched number of composite keys: #{cks.inspect} vs #{cpks.inspect}") unless cks.length == cpks.length
    1240:           uses_cks = opts[:uses_composite_keys] = cks.length > 1
    1241:           opts[:dataset] ||= proc do
    1242:             opts.associated_class.filter(Array(opts.qualified_key).zip(cpks.map{|k| send(k)}))
    1243:           end
    1244:           opts[:eager_loader] ||= proc do |eo|
    1245:             h = eo[:key_hash][elk]
    1246:             rows = eo[:rows]
    1247:             if one_to_one
    1248:               rows.each{|object| object.associations[name] = nil}
    1249:             else
    1250:               rows.each{|object| object.associations[name] = []}
    1251:             end
    1252:             reciprocal = opts.reciprocal
    1253:             klass = opts.associated_class
    1254:             filter_keys = opts.eager_loading_predicate_key
    1255:             ds = model.eager_loading_dataset(opts, klass.filter(filter_keys=>h.keys), nil, eo[:associations], eo)
    1256:             case opts.eager_limit_strategy
    1257:             when :distinct_on
    1258:               ds = ds.distinct(*filter_keys).order_prepend(*filter_keys)
    1259:             when :window_function
    1260:               delete_rn = true
    1261:               rn = ds.row_number_column
    1262:               ds = apply_window_function_eager_limit_strategy(ds, opts)
    1263:             when :correlated_subquery
    1264:               ds = apply_correlated_subquery_eager_limit_strategy(ds, opts) do |xds|
    1265:                 xds.where(opts.associated_object_keys.map{|k| [SQL::QualifiedIdentifier.new(xds.first_source_alias, k), SQL::QualifiedIdentifier.new(xds.first_source_table, k)]})
    1266:               end
    1267:             end
    1268:             ds.all do |assoc_record|
    1269:               assoc_record.values.delete(rn) if delete_rn
    1270:               hash_key = uses_cks ? km.map{|k| assoc_record.send(k)} : assoc_record.send(km)
    1271:               next unless objects = h[hash_key]
    1272:               if one_to_one
    1273:                 objects.each do |object|
    1274:                   unless object.associations[name]
    1275:                     object.associations[name] = assoc_record
    1276:                     assoc_record.associations[reciprocal] = object if reciprocal
    1277:                   end
    1278:                 end
    1279:               else
    1280:                 objects.each do |object|
    1281:                   object.associations[name].push(assoc_record)
    1282:                   assoc_record.associations[reciprocal] = object if reciprocal
    1283:                 end
    1284:               end
    1285:             end
    1286:             if opts.eager_limit_strategy == :ruby
    1287:               limit, offset = opts.limit_and_offset
    1288:               rows.each{|o| o.associations[name] = o.associations[name].slice(offset||0, limit) || []}
    1289:             end
    1290:           end
    1291:
    1292:           join_type = opts[:graph_join_type]
    1293:           select = opts[:graph_select]
    1294:           use_only_conditions = opts.include?(:graph_only_conditions)
    1295:           only_conditions = opts[:graph_only_conditions]
    1296:           conditions = opts[:graph_conditions]
    1297:           opts[:cartesian_product_number] ||= one_to_one ? 0 : 1
    1298:           graph_block = opts[:graph_block]
    1299:           opts[:eager_grapher] ||= proc do |eo|
    1300:             ds = eo[:self]
    1301:             ds = ds.graph(eager_graph_dataset(opts, eo), use_only_conditions ? only_conditions : cks.zip(pkcs) + conditions, eo.merge(:select=>select, :join_type=>join_type, :from_self_alias=>ds.opts[:eager_graph][:master]), &graph_block)
    1302:             # We only load reciprocals for one_to_many associations, as other reciprocals don't make sense
    1303:             ds.opts[:eager_graph][:reciprocals][eo[:table_alias]] = opts.reciprocal
    1304:             ds
    1305:           end
    1306:
    1307:           def_association_dataset_methods(opts)
    1308:
    1309:           ck_nil_hash ={}
    1310:           cks.each{|k| ck_nil_hash[k] = nil}
    1311:
    1312:           unless opts[:read_only]
    1313:             validate = opts[:validate]
    1314:
    1315:             if one_to_one
    1316:               association_module_private_def(opts._setter_method, opts) do |o|
    1317:                 up_ds = _apply_association_options(opts, opts.associated_class.filter(cks.zip(cpks.map{|k| send(k)})))
    1318:                 if o
    1319:                   up_ds = up_ds.exclude(o.pk_hash)
    1320:                   cks.zip(cpks).each{|k, pk| o.send(:"#{k}=", send(pk))}
    1321:                 end
    1322:                 checked_transaction do
    1323:                   up_ds.update(ck_nil_hash)
    1324:                   o.save(:validate=>validate) || raise(Sequel::Error, "invalid associated object, cannot save") if o
    1325:                 end
    1326:               end
    1327:               association_module_def(opts.setter_method, opts){|o| set_one_to_one_associated_object(opts, o)}
    1328:             else
    1329:               association_module_private_def(opts._add_method, opts) do |o|
    1330:                 cks.zip(cpks).each{|k, pk| o.send(:"#{k}=", send(pk))}
    1331:                 o.save(:validate=>validate) || raise(Sequel::Error, "invalid associated object, cannot save")
    1332:               end
    1333:               def_add_method(opts)
    1334:
    1335:               association_module_private_def(opts._remove_method, opts) do |o|
    1336:                 cks.each{|k| o.send(:"#{k}=", nil)}
    1337:                 o.save(:validate=>validate) || raise(Sequel::Error, "invalid associated object, cannot save")
    1338:               end
    1339:               association_module_private_def(opts._remove_all_method, opts) do
    1340:                 _apply_association_options(opts, opts.associated_class.filter(cks.zip(cpks.map{|k| send(k)}))).update(ck_nil_hash)
    1341:               end
    1342:               def_remove_methods(opts)
    1343:             end
    1344:           end
    1345:         end

def_one_to_one(opts) click to toggle source

Alias of def_one_to_many, since they share pretty much the same code.

          # File lib/sequel/model/associations.rb, line 1348
    1348:         def def_one_to_one(opts)
    1349:           def_one_to_many(opts)
    1350:         end

def_remove_methods(opts) click to toggle source

Add the remove_ and remove_all instance methods

          # File lib/sequel/model/associations.rb, line 1353
    1353:         def def_remove_methods(opts)
    1354:           association_module_def(opts.remove_method, opts){|o,*args| remove_associated_object(opts, o, *args)}
    1355:           association_module_def(opts.remove_all_method, opts){|*args| remove_all_associated_objects(opts, *args)}
    1356:         end

eager_graph_dataset(opts, eager_options) click to toggle source

Return dataset to graph into given the association reflection, applying the :callback option if set.

          # File lib/sequel/model/associations.rb, line 1359
    1359:         def eager_graph_dataset(opts, eager_options)
    1360:           ds = opts.associated_class.dataset
    1361:           if cb = eager_options[:callback]
    1362:             ds = cb.call(ds)
    1363:           end
    1364:           ds
    1365:         end

Disabled; run with --debug to generate this.

[Validate]

Generated with the Darkfish Rdoc Generator 1.1.6.