Active record pattern

From Wikipedia, the free encyclopedia

In computer science, the active record pattern is a design pattern frequently found in enterprise applications.

Active record is an approach to reading data from a database. A database table or view is wrapped into a class, thus an object instance is tied to a single row in the table. After creation of an object, a new row is added to the table upon save. Any object loaded gets its information from the database; when an object is updated, the corresponding row in the table is also updated. The wrapper class implements accessor methods for each column in the table or view.

Implementations of Active Record can be found in the CakePHP and Ruby on Rails frameworks. For example, if there's a table parts with columns id (serial primary key), name (varchar type) and price (money or double precision type), and there's a class Part, the following code:

a = Part.new
a.name = "Sample part"
a.price = 123.45
a.save

will create a new row in the database with the given values, and is roughly equivalent to the SQL command

INSERT INTO parts (name, price) VALUES ('Sample part', 123.45);

Conversely, the class can be used to query the database:

widgetname = "gearbox"
b = Part.find(:first, :conditions => [ "name = ?", widgetname ])

will create an object from the first row of the database whose name column is equal to the contents of the Ruby variable widgetname, and is roughly equal to the SQL command

SELECT * FROM parts WHERE name = 'gearbox' LIMIT 1;

Alternatively, the above code could have been shortened:

b = Part.find_by_name("gearbox")

[edit] External links

In other languages