123456789_123456789_123456789_123456789_123456789_

Active Record – Object-relational mapping in 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.

You can read more about Active Record in the Active Record Basics guide.

A short rundown of some of the major features:

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

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

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

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:

Admit the Database:

Download and installation

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

$ gem install activerecord

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

License

Active Record is released under the MIT license:

Support

API documentation is at:

Bug reports for the Ruby on Rails project can be filed here:

Feature requests should be discussed on the rails-core mailing list here: