Ruby on Rails

ActiveRecord Model Relations

orders
id int
customer_id int
line_items
id int
order_id int
customers
id int
name string
addresses
id int
customer_id int
#Notice that the classes are in the Singular
class Order < ActiveRecord::Base
  has_many :line_items
  belongs_to :customer #there is a column customer_id in the table
end

class LineItem < ActiveRecord::Base
  belongs_to :order #there is a column order_id in the table
end

class Customer < ActiveRecord::Base
  has_many :orders
  has_one :address
end

class Address < ActiveRecord::Base
  belongs_to :customer
end

#It inherits a LOT of methods from ActiveRecord

myorder = Order.create(:customer_id => 33)

myorder.customer_id #get the customer_id for this order

myorder.name #gets Customer's name (assume 'name' column in customer table)

Order.find(:all) #all orders

#Other examples (assume the Company model has been defined with the appropriate columns).
Company.find(:first, :conditions => [
    "id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
    { :id => 3, :name => "37signals", :division => "First", :accounting_date => '2005-01-01' }
])

Student.find(:all, :conditions => { :grade => 9..12 })




José M. Vidal .

6 of 16