Report erratum
Prepared exclusively for Jordan A. Fowler
In addition, the Rails classes that wrap our database tables provide a set of class-level methodsthatperformtable-level operations.For example, we might need to .nd the order with a particular id. This is implemented as a class method that returns the corresponding Order object.InRuby code, this might class method
page 634 ��.
looklike
order = Order.find(1) puts
page 632 ��.
puts "Order #{order.customer_id}, amount=#{order.amount}"
Sometimes these class-levelmethods return collections of objects.
iterating
page 639 ��.
Order.find(:all, :conditions => "name='dave'" ).each do |order|
puts order.amount
end
Finally,the objects corresponding toindividual rowsin atablehave methods that operate on that row.Probably the most widely usedis save, the operation that saves the row to thedatabase.
Order.find(:all, :conditions => "name='dave'" ).each do |order|
order.discount = 0.5
order.save
end
So an ORM layer maps tables to classes, rows to objects, and columns to attributes ofthose objects.Class methods are usedtoperformtable-leveloper-ations, andinstance methodsperform operations on theindividual rows.
In a typical ORM library, you supply con.guration data to specify the map-pings between entities in the database and entities in the program. Program-mersusing theseORM toolsoften .nd themselvescreating and maintaining a boatload ofXML con.guration .les.
Active Record
ActiveRecord is theORMlayer suppliedwithRails.It closelyfollows the stan-dardORMmodel:tables mapto classes, rowsto objects, and columnsto object attributes.Itdiffersfrom most otherORMlibrariesin the wayitis con.gured. By relying on convention and starting with sensible defaults, Active Record minimizes the amount of con.guration that developers perform. To illustrate this,here�fs aprogram that usesActiveRecord to wrap our orders table.
require 'active_record'
class Order < ActiveRecord::Base
end
order = Order.find(1)
order.discount = 0.5
order.save
Report erratum
Prepared exclusively for Jordan A. Fowler
This code usesthe newOrder classtofetchthe order with anid of1 and modify thediscount.(We�fve omittedthe codethat creates adatabase connectionfor now.) Active Record relieves us of the hassles of dealing with the underlying database,leaving usfree to work onbusinesslogic.
But Active Record does more than that. As you�fll see when we develop our shopping cart application, starting onpage 62,ActiveRecordintegrates seam-lesslywiththe rest of theRailsframework.If a webform sends the application datarelated to abusinessobject,ActiveRecord can extractitintoour model. ActiveRecord supports sophisticated validation of modeldata, andif theform datafails validations,theRails views can extract andformat errors withjust a singleline of code.
Agile Web Development with Rails
Start from the beginning
