CS6320:  SW Engineering of Web Based Systems

 

RoR: Database Associations ---how to declare and use them

(from RoR Guide)

Why Associations between Models?

  • common operations simpler and easier (look later)

What are the Associations you can declare in a Model (in relation to another Model)

  • belongs_to

  • has_one

  • has_many

  • has_many :through

  • has_one :through

  • has_and_belongs_to_many

 

 

Example of how to declare Associations in your Modles (has_many, belongs_to, etc.)

model for customers and a model for orders.

  • Each customer can have many orders. Without associations, the model declarations would look like this:

class Customer < ActiveRecord::Base
  has_many :orders, dependent: :destroy
end
 
class Order < ActiveRecord::Base
  belongs_to :customer
end

Special Tip: Notice when we use has_many we reference the model as PLURAL -- this is convention in RoR you MUST Adhere to. But, for belongs_to it is the singular.

 

Example of How easier with Associations

Without Associations

class Customer < ActiveRecord::Base
end
 
class Order < ActiveRecord::Base
end

Add New Order:

@order = Order.create(order_date: Time.now, customer_id: @customer.id)

Deleting a customer, and ensuring that all of its orders get deleted as well:

@orders = Order.where(customer_id: @customer.id)
@orders.each do |order|
  order.destroy
end
@customer.destroy

Looking up all of a Customer's orders

@customer = Customer.where(*****);

@orders = Order.where(customer_id: @customer.id);

 

 

With Associations

...see above definition with Associations of model classes.

Add new Order is easier:

@order = @customer.orders.create(order_date: Time.now)

Deleting a customer and all of its orders is much easier:

@customer.destroy

 

 

Looking up all of a Customer's orders (is a bit easier --at least if you were doing the second step in a view you wouldn't be contacting the Model class directly)

@customer = Customer.where(*****);

#this gets all orders associated with this customer
@orders = @customer.orders;    

 

 

 

 

© Lynne Grewe