File: README.rdoc [activerecord-3.2.22 Documentation]

### Home Classes Methods

### Files

- README.rdoc

### Class Index

Quicksearch

- ActiveRecord
- ActiveRecord::ActiveRecordError
- ActiveRecord::AdapterNotFound
- ActiveRecord::AdapterNotSpecified
- ActiveRecord::Aggregations
- ActiveRecord::Aggregations::ClassMethods
- ActiveRecord::AssociationTypeMismatch
- ActiveRecord::Associations
- ActiveRecord::Associations::ClassMethods
- ActiveRecord::AttributeAssignment
- ActiveRecord::AttributeAssignment::ClassMethods
- ActiveRecord::AttributeAssignmentError
- ActiveRecord::AttributeMethods
- ActiveRecord::AttributeMethods::BeforeTypeCast
- ActiveRecord::AttributeMethods::ClassMethods
- ActiveRecord::AttributeMethods::DeprecatedUnderscoreRead
- ActiveRecord::AttributeMethods::DeprecatedUnderscoreRead::ClassMethods
- ActiveRecord::AttributeMethods::Dirty
- ActiveRecord::AttributeMethods::PrimaryKey
- ActiveRecord::AttributeMethods::PrimaryKey::ClassMethods
- ActiveRecord::AttributeMethods::Query
- ActiveRecord::AttributeMethods::Read
- ActiveRecord::AttributeMethods::Read::ClassMethods
- ActiveRecord::AttributeMethods::Serialization
- ActiveRecord::AttributeMethods::Serialization::Attribute
- ActiveRecord::AttributeMethods::Serialization::ClassMethods
- ActiveRecord::AttributeMethods::TimeZoneConversion
- ActiveRecord::AttributeMethods::TimeZoneConversion::ClassMethods
- ActiveRecord::AttributeMethods::Write
- ActiveRecord::AttributeMethods::Write::ClassMethods
- ActiveRecord::AutosaveAssociation
- ActiveRecord::AutosaveAssociation::ClassMethods
- ActiveRecord::Base
- ActiveRecord::Batches
- ActiveRecord::Calculations
- ActiveRecord::Callbacks
- ActiveRecord::Coders
- ActiveRecord::ConfigurationError
- ActiveRecord::ConnectionAdapters
- ActiveRecord::ConnectionAdapters::AbstractAdapter
- ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter
- ActiveRecord::ConnectionAdapters::ConnectionHandler
- ActiveRecord::ConnectionAdapters::ConnectionManagement
- ActiveRecord::ConnectionAdapters::ConnectionPool
- ActiveRecord::ConnectionAdapters::DatabaseLimits
- ActiveRecord::ConnectionAdapters::DatabaseStatements
- ActiveRecord::ConnectionAdapters::Mysql2Adapter
- ActiveRecord::ConnectionAdapters::MysqlAdapter
- ActiveRecord::ConnectionAdapters::MysqlAdapter::StatementPool
- ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
- ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::StatementPool
- ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::TableDefinition
- ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::Utils
- ActiveRecord::ConnectionAdapters::PostgreSQLColumn
- ActiveRecord::ConnectionAdapters::QueryCache
- ActiveRecord::ConnectionAdapters::Quoting
- ActiveRecord::ConnectionAdapters::SQLiteAdapter
- ActiveRecord::ConnectionAdapters::SQLiteAdapter::ExplainPrettyPrinter
- ActiveRecord::ConnectionAdapters::SQLiteAdapter::StatementPool
- ActiveRecord::ConnectionAdapters::SQLiteAdapter::Version
- ActiveRecord::ConnectionAdapters::SchemaCache
- ActiveRecord::ConnectionAdapters::SchemaStatements
- ActiveRecord::ConnectionAdapters::StatementPool
- ActiveRecord::ConnectionAdapters::Table
- ActiveRecord::ConnectionAdapters::TableDefinition
- ActiveRecord::ConnectionNotEstablished
- ActiveRecord::ConnectionTimeoutError
- ActiveRecord::CounterCache
- ActiveRecord::DangerousAttributeError
- ActiveRecord::Delegation
- ActiveRecord::DynamicFinderMatch
- ActiveRecord::DynamicMatchers
- ActiveRecord::DynamicScopeMatch
- ActiveRecord::Explain
- ActiveRecord::FinderMethods
- ActiveRecord::Fixtures
- ActiveRecord::Fixtures::File
- ActiveRecord::Generators
- ActiveRecord::Generators::Migration
- ActiveRecord::Generators::MigrationGenerator
- ActiveRecord::Generators::ModelGenerator
- ActiveRecord::Generators::ObserverGenerator
- ActiveRecord::Generators::SessionMigrationGenerator
- ActiveRecord::IdentityMap
- ActiveRecord::IdentityMap::Middleware
- ActiveRecord::Inheritance
- ActiveRecord::Inheritance::ClassMethods
- ActiveRecord::Integration
- ActiveRecord::InvalidForeignKey
- ActiveRecord::IrreversibleMigration
- ActiveRecord::Locking
- ActiveRecord::Locking::Optimistic
- ActiveRecord::Locking::Optimistic::ClassMethods
- ActiveRecord::Locking::Pessimistic
- ActiveRecord::LogSubscriber
- ActiveRecord::Migration
- ActiveRecord::Migration::CommandRecorder
- ActiveRecord::MigrationProxy
- ActiveRecord::ModelSchema
- ActiveRecord::ModelSchema::ClassMethods
- ActiveRecord::MultiparameterAssignmentErrors
- ActiveRecord::NestedAttributes
- ActiveRecord::NestedAttributes::ClassMethods
- ActiveRecord::NestedAttributes::TooManyRecords
- ActiveRecord::Observer
- ActiveRecord::Persistence
- ActiveRecord::Persistence::ClassMethods
- ActiveRecord::PreparedStatementInvalid
- ActiveRecord::QueryCache
- ActiveRecord::QueryCache::ClassMethods
- ActiveRecord::QueryMethods
- ActiveRecord::Querying
- ActiveRecord::Railtie
- ActiveRecord::Railties
- ActiveRecord::Railties::ControllerRuntime
- ActiveRecord::Railties::ControllerRuntime::ClassMethods
- ActiveRecord::ReadOnlyRecord
- ActiveRecord::ReadonlyAttributes
- ActiveRecord::ReadonlyAttributes::ClassMethods
- ActiveRecord::RecordInvalid
- ActiveRecord::RecordNotFound
- ActiveRecord::RecordNotSaved
- ActiveRecord::RecordNotUnique
- ActiveRecord::Reflection
- ActiveRecord::Reflection::ClassMethods
- ActiveRecord::Reflection::MacroReflection
- ActiveRecord::Result
- ActiveRecord::Rollback
- ActiveRecord::Sanitization
- ActiveRecord::Sanitization::ClassMethods
- ActiveRecord::Schema
- ActiveRecord::Scoping
- ActiveRecord::Scoping::ClassMethods
- ActiveRecord::Scoping::Default
- ActiveRecord::Scoping::Default::ClassMethods
- ActiveRecord::Scoping::Named
- ActiveRecord::Scoping::Named::ClassMethods
- ActiveRecord::Serialization
- ActiveRecord::SerializationTypeMismatch
- ActiveRecord::SessionStore
- ActiveRecord::SessionStore::Session
- ActiveRecord::SessionStore::SqlBypass
- ActiveRecord::SpawnMethods
- ActiveRecord::StaleObjectError
- ActiveRecord::StatementInvalid
- ActiveRecord::Store
- ActiveRecord::Store::ClassMethods
- ActiveRecord::TestFixtures
- ActiveRecord::TestFixtures::ClassMethods
- ActiveRecord::ThrowResult
- ActiveRecord::Timestamp
- ActiveRecord::Transactions
- ActiveRecord::Transactions::ClassMethods
- ActiveRecord::Translation
- ActiveRecord::UnknownAttributeError
- ActiveRecord::UnknownPrimaryKey
- ActiveRecord::Validations
- ActiveRecord::Validations::AssociatedValidator
- ActiveRecord::Validations::ClassMethods
- ActiveRecord::Validations::UniquenessValidator
- ActiveRecord::WrappedDatabaseException
- Mysql
- Mysql::Result
- Mysql::Stmt
- Mysql::Time
- ArJdbcMySQL
- ArJdbcMySQL::Error

No matching classes.

# Active Record -- Object-relational mapping put on rails

Active Record connects classes to relational database tables to establish an almost zero-configuration persistence layer for applications. The library provides a base class that, when subclassed, sets up a mapping between the new class and an existing table in the database. In the context of an application, these classes are commonly referred to as models. Models can also be connected to other models; this is done by defining associations.

Active Record relies heavily on naming in that it uses class and association names to establish mappings between respective database tables and foreign key columns. Although these mappings can be defined explicitly, it's recommended to follow naming conventions, especially when getting started with the library.

A short rundown of some of the major features:

- Automated mapping between classes and tables, attributes and columns.

      class Product < ActiveRecord::Base
      end

      The Product class is automatically mapped to the table named "products",
      which might look like this:

      CREATE TABLE products (
        id int(11) NOT NULL auto_increment,
        name varchar(255),
        PRIMARY KEY  (id)
      );

      This would also define the following accessors: `Product#name` and
      `Product#name=(new_name)`

  Learn more

- Associations between objects defined by simple class methods.

      class Firm < ActiveRecord::Base
        has_many   :clients
        has_one    :account
        belongs_to :conglomerate
      end

  Learn more

- Aggregations of value objects.

      class Account < ActiveRecord::Base
        composed_of :balance, :class_name => "Money",
                    :mapping => %w(balance amount)
        composed_of :address,
                    :mapping => [%w(address_street street), %w(address_city city)]
      end

  Learn more

- Validation rules that can differ for new or existing objects.

      class Account < ActiveRecord::Base
        validates_presence_of     :subdomain, :name, :email_address, :password
        validates_uniqueness_of   :subdomain
        validates_acceptance_of   :terms_of_service, :on => :create
        validates_confirmation_of :password, :email_address, :on => :create
      end

  Learn more

- Callbacks available for the entire life cycle (instantiation, saving, destroying, validating, etc.).

      class Person < ActiveRecord::Base
        before_destroy :invalidate_payment_plan
        # the `invalidate_payment_plan` method gets called just before Person#destroy
      end

  Learn more

- Observers that react to changes in a model.

      class CommentObserver < ActiveRecord::Observer
        def after_create(comment) # is called just after Comment#save
          CommentMailer.new_comment_email("david@loudthinking.com", comment).deliver
        end
      end

  Learn more

- Inheritance hierarchies.

      class Company < ActiveRecord::Base; end
      class Firm < Company; end
      class Client < Company; end
      class PriorityClient < Client; end

  Learn more

- Transactions.

      # Database transaction
      Account.transaction do
        david.withdrawal(100)
        mary.deposit(100)
      end

  Learn more

- Reflections on columns, associations, and aggregations.

      reflection = Firm.reflect_on_association(:clients)
      reflection.klass # => Client (class)
      Firm.columns # Returns an array of column descriptors for the firms table

  Learn more

- Database abstraction through simple adapters.

      # connect to SQLite3
      ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => "dbfile.sqlite3")

      # connect to MySQL with authentication
      ActiveRecord::Base.establish_connection(
        :adapter  => "mysql2",
        :host     => "localhost",
        :username => "me",
        :password => "secret",
        :database => "activerecord"
      )

  Learn more and read about the built-in support for MySQL, PostgreSQL, and SQLite3.

- Logging support for Log4r and Logger.

      ActiveRecord::Base.logger = Logger.new(STDOUT)
      ActiveRecord::Base.logger = Log4r::Logger.new("Application Log")

- Database agnostic schema management with Migrations.

      class AddSystemSettings < ActiveRecord::Migration
        def up
          create_table :system_settings do |t|
            t.string  :name
            t.string  :label
            t.text    :value
            t.string  :type
            t.integer :position
          end

          SystemSetting.create :name => "notice", :label => "Use notice?", :value => 1
        end

        def down
          drop_table :system_settings
        end
      end

  Learn more

## Philosophy

Active Record is an implementation of the object-relational mapping (ORM) pattern by the same name described by Martin Fowler:

    "An object that wraps a row in a database table or view,
    encapsulates the database access, and adds domain logic on that data."

Active Record attempts to provide a coherent wrapper as a solution for the inconvenience that is object-relational mapping. The prime directive for this mapping has been to minimize the amount of code needed to build a real-world domain model. This is made possible by relying on a number of conventions that make it easy for Active Record to infer complex relations and structures from a minimal amount of explicit direction.

Convention over Configuration:

- No XML-files!

- Lots of reflection and run-time extension

- Magic is not inherently a bad word

Admit the Database:

- Lets you drop down to SQL for odd cases and performance

- Doesn't attempt to duplicate or replace data definitions

## Download and installation

The latest version of Active Record can be installed with RubyGems:

    % [sudo] gem install activerecord

Source code can be downloaded as part of the Rails project on GitHub

- github.com/rails/rails/tree/3-2-stable/activerecord

## License

Active Record is released under the MIT license.

## Support

API documentation is at

- api.rubyonrails.org

Bug reports and feature requests can be filed with the rest for the Ruby on Rails project here:

- github.com/rails/rails/issues

[Validate]

Generated with the Darkfish Rdoc Generator 2.