Files

Class Index [+]

Quicksearch

Active Record – Object-relation mapping put on rails

Active Record connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. It’s an implementation of the object-relational mapping (ORM) pattern by the same name as 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’s main contribution to the pattern is to relieve the original of two stunting problems: lack of associations and inheritance. By adding a simple domain language-like set of macros to describe the former and integrating the Single Table Inheritance pattern for the latter, Active Record narrows the gap of functionality between the data mapper and active record approach.

A short rundown of the major features:

Simple example (1/2): Defining tables and classes (using MySQL)

Data definitions are specified only in the database. Active Record queries the database for the column names (that then serves to determine which attributes are valid) on regular object instantiation through the new constructor and relies on the column names in the rows with the finders.

# CREATE TABLE companies (
#   id int(11) unsigned NOT NULL auto_increment,
#   client_of int(11),
#   name varchar(255),
#   type varchar(100),
#   PRIMARY KEY  (id)
# )

Active Record automatically links the “Company” object to the “companies” table

class Company < ActiveRecord::Base
  has_many :people, :class_name => "Person"
end

class Firm < Company
  has_many :clients

  def people_with_all_clients
   clients.inject([]) { |people, client| people + client.people }
  end
end

The foreign_key is only necessary because we didn’t use “firm_id” in the data definition

class Client < Company
  belongs_to :firm, :foreign_key => "client_of"
end

# CREATE TABLE people (
#   id int(11) unsigned NOT NULL auto_increment,
#   name text,
#   company_id text,
#   PRIMARY KEY  (id)
# )

Active Record will also automatically link the “Person” object to the “people” table

class Person < ActiveRecord::Base
  belongs_to :company
end

Simple example (2/2): Using the domain

Picking a database connection for all the Active Records

ActiveRecord::Base.establish_connection(
  :adapter  => "mysql", 
  :host     => "localhost", 
  :username => "me", 
  :password => "secret", 
  :database => "activerecord"
)

Create some fixtures

firm = Firm.new("name" => "Next Angle")
# SQL: INSERT INTO companies (name, type) VALUES("Next Angle", "Firm")
firm.save

client = Client.new("name" => "37signals", "client_of" => firm.id)
# SQL: INSERT INTO companies (name, client_of, type) VALUES("37signals", 1, "Firm")
client.save

Lots of different finders

# SQL: SELECT * FROM companies WHERE id = 1
next_angle = Company.find(1)

# SQL: SELECT * FROM companies WHERE id = 1 AND type = 'Firm'
next_angle = Firm.find(1)    

# SQL: SELECT * FROM companies WHERE id = 1 AND name = 'Next Angle'
next_angle = Company.find(:first, :conditions => "name = 'Next Angle'")

next_angle = Firm.find_by_sql("SELECT * FROM companies WHERE id = 1").first

The supertype, Company, will return subtype instances

Firm === next_angle

All the dynamic methods added by the has_many macro

next_angle.clients.empty?  # true
next_angle.clients.size    # total number of clients
all_clients = next_angle.clients

Constrained finds makes access security easier when ID comes from a web-app

# SQL: SELECT * FROM companies WHERE client_of = 1 AND type = 'Client' AND id = 2
thirty_seven_signals = next_angle.clients.find(2)

Bi-directional associations thanks to the “belongs_to” macro

thirty_seven_signals.firm.nil? # true

Philosophy

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

The latest version of Active Record can be found at

Documentation can be found at

Installation

The prefered method of installing Active Record is through its GEM file. You’ll need to have RubyGems installed for that, though. If you have, then use:

% [sudo] gem install activerecord-1.10.0.gem

You can also install Active Record the old-fashioned way with the following command:

% [sudo] ruby install.rb

from its distribution directory.

License

Active Record is released under the MIT license.

Support

The Active Record homepage is www.rubyonrails.com. You can find the Active Record RubyForge page at rubyforge.org/projects/activerecord. And as Jim from Rake says:

Feel free to submit commits or feature requests.  If you send a patch,
remember to update the corresponding unit tests.  If fact, I prefer
new feature to be submitted in the form of new unit tests.

For other information, feel free to ask on the rubyonrails-talk (groups.google.com/group/rubyonrails-talk) mailing list.

[Validate]

Generated with the Darkfish Rdoc Generator 2.