Data Access Objects - Rails Style

Most other DAOs you have to create some configuration file, whether xml or ini files or created manually. Example, to setup Pear's DB_DataObject, you must create an ini file and run a script "createTables.php" each time your database changes. Not so with RoR! its automagically created and updated for you. It does ALL the basic CRUD for you. Just have to specify the relationships (if any).

Say you have tables:

id int(11) NOT NULL auto_increment,
name varchar(255),

CREATE TABLE companies (
id int(11) NOT NULL auto_increment,
name varchar(255),

Naming Convention
By the way, RoR has a naming convention for tables. You name the table the plural version of the word. The primary key has to be ID in each table, foreign keys are _id. EGADS! It almost looks like English, huh? An average half-way intelligent person could even read it and have a clue of what’s going on. Even pointy haired bosses. Though, in traditional fashion, some people have to complain about having to name their tables a certain way. (violin music playing) There is a way to turn off "plural/singular" in the settings. So if you just have to be difficult, here ya go.
In your config/environment.rb file add:
ActiveRecord::Base.pluralize_table_names = false

Dave has an amusing blog entry: 10 Reasons Rails Does Pluralization

You can also set the name manually in your class definition if you have legacy tables or you can't name them plural:

class Company < ActiveRecord::Base
set_table_name company

You create the definitions like:

class Person < ActiveRecord::Base;

class Company < ActiveRecord::Base;

Creating data
person = Person.create( :name => "Nola Stowe");
This instantiates the model object and saves to database. Bah-Da-Bing!!

Finding Data
If you knew my id, you can find me with:

nola = Person.find(1)

or by name

nola = Person.find(:first,
:condition "name = 'Nola Stowe'"

To find the first record with the name of Nola, use ":all" to find all.

Dynamic Finders
When you have only one criteria, you can one of the dynamic finders, find_by_field OR find_all_by_field

onePerson = person.find_by_name("Nola Stowe");
allPersons = person.find_all_by_name("Nola Stowe");


If I have explained something incorrectly, let me know. I am a bit nervous writing about something I’m learning as I go.

Next I will explore using more of ActiveRecord.

Updated to clairify this is RoR not Ruby conventions, Thanks Michael Nguyen


Right! thanks... learning both at once I have to remember Ruby is separete from Rails.