Why ORM with Active/Record(AR) and Rails
From CLUG Wiki
ORM and AR (Is this a buddist chant?)
I must include a link that, for me, explains why its great to work with rails >> Pursuit of Beauty
First some definitions:
Active Record is the object-relational mapping (ORM) layer supplied with Rails. (AR is also used outside the rails framework.) Active Record closely follows the standard ORM model: tables map to classes, rows to objects, and columns to object attributes
One of the reasons RoR (Ruby on Rails) has been so succesful is the integration of the ORM layer into the framework
A Rails characteristic is the Model-View-Controller (MVC) architecture of the framework
In Rails, AR is represented in the M(Model) of the MVC architecture. Following the rule of convention, AR uses the singular in the model class and the plural in the database table. i.e. A people table would have a person model class. The conventions make the code and framework easier to read and understand as well as speeding up development.
End of definitions!
It may well be a chant!
An example.
I wont go through the installation and setup of rails and ruby, please go to the site for that.
*************The DDL*********************
CREATE TABLE `accounts` ( `id` int(11) NOT NULL auto_increment, `name` varchar(200) NOT NULL default , `created_on` datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY (`id`) ) TYPE=MyISAM
CREATE TABLE `people` ( `id` int(11) NOT NULL auto_increment, `title` varchar(200) NOT NULL default , `email` varchar(200) NOT NULL default , PRIMARY KEY (`id`) ) TYPE=MyISAM
CREATE TABLE `accounts_people` ( `account_id` int(11) NOT NULL default '0', `person_id` int(11) NOT NULL default '0', `created_on` timestamp(14) NOT NULL, `credit` float NOT NULL default '0', `debit` float NOT NULL default '0' ) TYPE=MyISAM
**************THe models*****************
class Account < ActiveRecord::Base has_and_belongs_to_many :people end
class Person < ActiveRecord::Base has_and_belongs_to_many :accounts end
*************Operating in the console**************
pers1 = Person.create(:title => "billy grunt") pers2 = Person.find(1)
acc1 = Account.new(:name => "High kicks") acc2 = Account.new(:name => "Bingbong") acc3 = Account.find(4)
pers1.accounts.push_with_attributes(acc1, :debit => 200) pers1.accounts.push_with_attributes(acc2, :debit => 200, :credit => 2009) pers1.accounts.push_with_attributes(acc3, :credit => 200) pers2.accounts.push_with_attributes(acc1, :credit => 200)
account = Account.find_by_name("High Kicks")
account.people.each {|a| puts a.debit}
account.people.each {|a| puts a.credit}
person = Person.find_by_title("billy grunt")
person.accounts.each{|a| puts a.credit}
Thats it! a complete accounts system with only 2 lines of code!
