Module: ActiveRecord::AssociationPreload::ClassMethods

### Home Classes Methods

### In Files

- lib/active_record/association_preload.rb

### Methods

- #preload_associations

### Files

- README.rdoc

### Class/Module Index

Quicksearch

- ActiveRecord
- ActiveRecord::ActiveRecordError
- ActiveRecord::AdapterNotFound
- ActiveRecord::AdapterNotSpecified
- ActiveRecord::Aggregations
- ActiveRecord::Aggregations::ClassMethods
- ActiveRecord::AssociationPreload
- ActiveRecord::AssociationPreload::ClassMethods
- ActiveRecord::AssociationTypeMismatch
- ActiveRecord::Associations
- ActiveRecord::Associations::ClassMethods
- ActiveRecord::Associations::HasOneThroughAssociation
- ActiveRecord::Associations::ThroughAssociationScope
- ActiveRecord::AttributeAssignmentError
- ActiveRecord::AttributeMethods
- ActiveRecord::AttributeMethods::BeforeTypeCast
- ActiveRecord::AttributeMethods::ClassMethods
- ActiveRecord::AttributeMethods::Dirty
- ActiveRecord::AttributeMethods::PrimaryKey
- ActiveRecord::AttributeMethods::PrimaryKey::ClassMethods
- ActiveRecord::AttributeMethods::Query
- ActiveRecord::AttributeMethods::Read
- ActiveRecord::AttributeMethods::Read::ClassMethods
- ActiveRecord::AttributeMethods::TimeZoneConversion
- ActiveRecord::AttributeMethods::TimeZoneConversion::ClassMethods
- ActiveRecord::AttributeMethods::Write
- ActiveRecord::AttributeMethods::Write::ClassMethods
- ActiveRecord::AutosaveAssociation
- ActiveRecord::AutosaveAssociation::ClassMethods
- ActiveRecord::Base
- ActiveRecord::Calculations
- ActiveRecord::Callbacks
- ActiveRecord::Callbacks::ClassMethods
- ActiveRecord::ConfigurationError
- ActiveRecord::ConnectionAdapters
- ActiveRecord::ConnectionAdapters::AbstractAdapter
- ActiveRecord::ConnectionAdapters::Column
- ActiveRecord::ConnectionAdapters::Column::Format
- ActiveRecord::ConnectionAdapters::ConnectionHandler
- ActiveRecord::ConnectionAdapters::ConnectionManagement
- ActiveRecord::ConnectionAdapters::ConnectionPool
- ActiveRecord::ConnectionAdapters::DatabaseLimits
- ActiveRecord::ConnectionAdapters::DatabaseStatements
- ActiveRecord::ConnectionAdapters::MysqlAdapter
- ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
- ActiveRecord::ConnectionAdapters::PostgreSQLColumn
- ActiveRecord::ConnectionAdapters::QueryCache
- ActiveRecord::ConnectionAdapters::Quoting
- ActiveRecord::ConnectionAdapters::SQLiteAdapter
- ActiveRecord::ConnectionAdapters::SQLiteAdapter::Version
- ActiveRecord::ConnectionAdapters::SchemaStatements
- ActiveRecord::ConnectionAdapters::Table
- ActiveRecord::ConnectionAdapters::TableDefinition
- ActiveRecord::ConnectionNotEstablished
- ActiveRecord::ConnectionTimeoutError
- ActiveRecord::CounterCache
- ActiveRecord::DangerousAttributeError
- ActiveRecord::DynamicFinderMatch
- ActiveRecord::DynamicScopeMatch
- ActiveRecord::FinderMethods
- ActiveRecord::Generators
- ActiveRecord::Generators::Migration
- ActiveRecord::Generators::MigrationGenerator
- ActiveRecord::Generators::ModelGenerator
- ActiveRecord::Generators::ObserverGenerator
- ActiveRecord::Generators::SessionMigrationGenerator
- ActiveRecord::InvalidForeignKey
- ActiveRecord::IrreversibleMigration
- ActiveRecord::Locking
- ActiveRecord::Locking::Optimistic
- ActiveRecord::Locking::Optimistic::ClassMethods
- ActiveRecord::Locking::Pessimistic
- ActiveRecord::LogSubscriber
- ActiveRecord::Migration
- ActiveRecord::MigrationProxy
- ActiveRecord::MultiparameterAssignmentErrors
- ActiveRecord::NamedScope
- ActiveRecord::NamedScope::ClassMethods
- ActiveRecord::NestedAttributes
- ActiveRecord::NestedAttributes::ClassMethods
- ActiveRecord::NestedAttributes::TooManyRecords
- ActiveRecord::Observer
- ActiveRecord::Persistence
- ActiveRecord::PredicateBuilder
- ActiveRecord::PreparedStatementInvalid
- ActiveRecord::QueryCache
- ActiveRecord::QueryCache::ClassMethods
- ActiveRecord::QueryMethods
- ActiveRecord::Railtie
- ActiveRecord::Railties
- ActiveRecord::Railties::ControllerRuntime
- ActiveRecord::Railties::ControllerRuntime::ClassMethods
- ActiveRecord::ReadOnlyRecord
- ActiveRecord::RecordInvalid
- ActiveRecord::RecordNotFound
- ActiveRecord::RecordNotSaved
- ActiveRecord::RecordNotUnique
- ActiveRecord::Reflection
- ActiveRecord::Reflection::ClassMethods
- ActiveRecord::Reflection::MacroReflection
- ActiveRecord::Relation
- ActiveRecord::Rollback
- ActiveRecord::Schema
- ActiveRecord::Serialization
- ActiveRecord::SerializationTypeMismatch
- ActiveRecord::SessionStore
- ActiveRecord::SessionStore::Session
- ActiveRecord::SessionStore::SqlBypass
- ActiveRecord::SpawnMethods
- ActiveRecord::StaleObjectError
- ActiveRecord::StatementInvalid
- ActiveRecord::TestFixtures
- ActiveRecord::TestFixtures::ClassMethods
- ActiveRecord::ThrowResult
- ActiveRecord::Timestamp
- ActiveRecord::Transactions
- ActiveRecord::Transactions::ClassMethods
- ActiveRecord::UnknownAttributeError
- ActiveRecord::Validations
- ActiveRecord::Validations::AssociatedValidator
- ActiveRecord::Validations::ClassMethods
- ActiveRecord::Validations::UniquenessValidator
- ActiveRecord::WrappedDatabaseException
- <
- Fixtures
- FixturesFileNotFound

No matching classes.

# ActiveRecord::AssociationPreload::ClassMethods

Implements the details of eager loading of Active Record associations. Application developers should not use this module directly.

`ActiveRecord::Base` is extended with this module. The source code in `ActiveRecord::Base` references methods defined in this module.

Note that ‘eager loading’ and ‘preloading’ are actually the same thing. However, there are two different eager loading strategies.

The first one is by using table joins. This was only strategy available prior to Rails 2.1. Suppose that you have an Author model with columns ‘name’ and ‘age’, and a Book model with columns ‘name’ and ‘sales’. Using this strategy, Active Record would try to retrieve all data for an author and all of its books via a single query:

    SELECT * FROM authors
    LEFT OUTER JOIN books ON authors.id = books.id
    WHERE authors.name = 'Ken Akamatsu'

However, this could result in many rows that contain redundant data. After having received the first row, we already have enough data to instantiate the Author object. In all subsequent rows, only the data for the joined ‘books’ table is useful; the joined ‘authors’ data is just redundant, and processing this redundant data takes memory and CPU time. The problem quickly becomes worse and worse as the level of eager loading increases (i.e. if Active Record is to eager load the associations’ associations as well).

The second strategy is to use multiple database queries, one for each level of association. Since Rails 2.1, this is the default strategy. In situations where a table join is necessary (e.g. when the `:conditions` option references an association’s column), it will fallback to the table join strategy.

See also ActiveRecord::Associations::ClassMethods, which explains eager loading in a more high-level (application developer-friendly) manner.

### Protected Instance Methods

preload_associations(records, associations, preload_options={}) click to toggle source

Eager loads the named associations for the given Active Record record(s).

In this description, ‘association name’ shall refer to the name passed to an association creation method. For example, a model that specifies `belongs_to :author`, `has_many :buyers` has association names `:author` and `:buyers`.

## Parameters

`records` is an array of ActiveRecord::Base. This array needs not be flat, i.e. `records` itself may also contain arrays of records. In any case, `preload_associations` will preload the all associations records by flattening `records`.

`associations` specifies one or more associations that you want to preload. It may be:

- a Symbol or a String which specifies a single association name. For example, specifying `:books` allows this method to preload all books for an Author.

- an Array which specifies multiple association names. This array is processed recursively. For example, specifying `[:avatar, :books]` allows this method to preload an author’s avatar as well as all of his books.

- a Hash which specifies multiple association names, as well as association names for the to-be-preloaded association objects. For example, specifying `{ :author => :avatar }` will preload a book’s author, as well as that author’s avatar.

`:associations` has the same format as the `:include` option for `ActiveRecord::Base.find`. So `associations` could look like this:

    :books
    [ :books, :author ]
    { :author => :avatar }
    [ :books, { :author => :avatar } ]

`preload_options` contains options that will be passed to ActiveRecord::Base#find (which is called under the hood for preloading records). But it is passed only one level deep in the `associations` argument, i.e. it's not passed to the child associations when `associations` is a Hash.

    # File lib/active_record/association_preload.rb, line 87
    def preload_associations(records, associations, preload_options={})
      records = Array.wrap(records).compact.uniq
      return if records.empty?
      case associations
      when Array then associations.each {|association| preload_associations(records, association, preload_options)}
      when Symbol, String then preload_one_association(records, associations.to_sym, preload_options)
      when Hash then
        associations.each do |parent, child|
          raise "parent must be an association name" unless parent.is_a?(String) || parent.is_a?(Symbol)
          preload_associations(records, parent, preload_options)
          reflection = reflections[parent]
          parents = records.sum { |record| Array.wrap(record.send(reflection.name)) }
          unless parents.empty?
            parents.first.class.preload_associations(parents, child)
          end
        end
      end
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.