英語版Wikipediaによるアクティブレコードバターン

Active record pattern - Wikipedia, the free encyclopedia http://en.wikipedia.org/wiki/Active_record_pattern の日本語訳

訳文

ソフトウェア工学において、アクティブレコードパターンは関係データベースにデータを保存するソフトウェアでよく使われるデザインパターンです。Marin Fowlerの本 Patterns of Enterprise Application Architectureで名付けられました。

In software engineering, the active record pattern is a design pattern frequently found in software that stores its data in relational databases. It was named by Martin Fowler in his book Patterns of Enterprise Application Architecture.

アクティブレコードは、データベース中のデータにアクセスするための方法です。データベースのテーブルやビューをクラスにラッピングし、テーブル中の一行をオブジェクトインスタンスに紐づけます。オブジェクトを作成し、保存すれば、テーブルに行が追加されます。オブジェクトをロードすると、データベースから情報が取得されます。オブジェクトを更新すると、テーブル中の対応する行が更新されます。ラッパクラスはテーブルまたはビューの各列にアクセスするためのメソッドやプロパティを実装します。

Active record is an approach to accessing data in 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 or properties for each column in the table or view.

このパターンはオブジェクト永続化ツールとオブジェクトリレーショナルマッピングで共通して使用されます。一般的に、外部キーによる関連は、プロパティが適切な型のオブジェクトインスタンスを返すことにより、表現されます。

This pattern is commonly used by object persistence tools, and in object-relational mapping. Typically foreign key relationships will be exposed as an object instance of the appropriate type via a property.

アクティブレコードの実装は、多くのプログラミング環境のさまざまなフレームワークで使われています。例えば、データベースでは、列name(文字列型)とprice(数値型)を含むテーブルpartsがある場合、クラスpartでアクティブレコードパターンを実装します。以下は仮のコードです:

Implementations of Active Record can be found in various frameworks for many programming environments. For example, if in a database there is a table parts with columns name (string type) and price (number type), and the Active Record pattern is implemented in the class Part, the following pseudo-code:

part = new Part()
part.name = "Sample part"
part.price = 123.45
part.save()

partsテーブルに新しい行を指定された値で作成します。ざっくり言えば以下のSQLコマンドと同じです。

will create a new row in the parts table 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:

b = Part.find_first("name", "gearbox")

これにより、partテーブルの行のうちname列の値が「gearbox」である最初の行をもとに、あらたなPartオブジェクトが作成されます。

This will create a new Part object based on the first matching row from the parts table whose name column has the value "gearbox". SQLコマンドは以下のようになります。

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