views:

23

answers:

1

Hey all,

I've heard all this talk about Rail's persistence engine (ActiveRecord). I did a search on it and I couldn't really get a clear idea of what it did. It seemed like it was an Object mapping to a database but that's all I came up with. If so do they save the objects to the database to maintain persistence? What are the advantages of using this model? What are the disadvantages?

Thanks! Matt Mueller

+1  A: 

Active Record is basically a pattern that maps classes to relational database tables. Objects represent rows in the database. The AR framework handles the saving and loading of these objects by generating the appropriate SQL statements for each database engine.

Example

Database Table              Active Record Class
-----------------------     --------------------------
People                   >  Person
-----------------------     --------------------------
FirstName : varchar(40)  >  string FirstName
LastName  : varchar(40)  >  string LastName

The framework gives you common methods to retrieve data in a database-independent way that integrates nicely with the programming language.

people = Person.GetAll()

Which generates and executes something along the lines of:

SELECT FirstName, LastName FROM People

What it's doing is reading the structure of the AR class and inferring the column names. The retrieved data is also mapped back to the class in the same manner.

The major advantage of this is that you remove the dependency on a single database engine. If you decide to switch from MySQL to SQLite, for example, a properly-coded AR framework can do this with almost no changes to your existing code.

A disadvantage, however, is that you are at the mercy of the particular AR framework that you're using. If it doesn't generate proper SQL in a certain situation or doesn't support a particular feature, you might have to fall back to writing it yourself, which defeats the purpose of database-independence.

David Brown
Thanks for the explanation!
Matt