Home arrow Ruby-on-Rails arrow Page 3 - Shopping Cart Implementation
RUBY-ON-RAILS

Shopping Cart Implementation


Continuing our series on setting up an online bookstore with Ruby-on-Rails, this two-part tutorial explains how to implement the shopping cart. It is excerpted from chapter five of the book Practical Rails Projects, written by Eldon Alameda (Apress; ISBN: 1590597818).

Author Info:
By: Apress Publishing
Rating: 5 stars5 stars5 stars5 stars5 stars / 13
May 28, 2010
TABLE OF CONTENTS:
  1. · Shopping Cart Implementation
  2. · Setting Up the Shopping Cart
  3. · Creating the Models
  4. · Modifying the Controller

print this article
SEARCH DEVARTICLES

Shopping Cart Implementation - Creating the Models
(Page 3 of 4 )

Before we can add anything to a shopping cart, we need to create two models: Cartfor the shopping carts themselves andCartItemfor books stored in a cart. It should come as no surprise that we use thescript/generatecommand to generate these models:  

$ script/generate model Cart

--------------------------------------------
  exists  app/models/
  exists  test/unit/
  exists  test/fixtures/
  create  app/models/cart.rb
  create  test/unit/cart_test.rb
  create  test/fixtures/carts.yml
  exists  db/migrate
  create  db/migrate/005_create_carts.rb
--------------------------------------------

$ script/generate model CartItem

--------------------------------------------

exists

app/models/

exists

test/unit/

exists

test/fixtures/

create

app/models/cart_item.rb

create

test/unit/cart_item_test.rb

create

test/fixtures/cart_items.yml

exists

db/migrate

create

db/migrate/006_create_cart_items.rb

Next, we need to specify the associations between the new (and some old) models. (ActiveRecord database relationships are covered in Chapter 3.) In our case, the cart items can be seen as a join model between a cart and books. In theory, we could have used a directhas_and_belongs_to_manyassociation between carts and books, but the items also need to store some data of their own. One example of such data is the quantity of a given book in a cart. Jill might want to buy one book for herself and one for her nephew Carl. We also need to store the price of a book at the time it was added to the cart so that it wonít change, even if the price of a book increased during the userís shopping session.

Therefore, we edit the model filesbook.rb,cart_item.rb, andcart.rbinapp/modelsto make the associations between carts, cart items, and books look as follows:

class Book < ActiveRecord::Base
Ö
  has_many :cart_items
  has_many :carts, :through => :cart_items
Ö
end

class CartItem < ActiveRecord::Base
  belongs_to :cart
  belongs_to :book
end

class Cart < ActiveRecord::Base
  has_many :cart_items
  has_many :books, :through => :cart_items
end

Note that we use the newhas_many :throughsyntax that was implemented in Rails 1.1. With the new syntax, we can access books belonging to a cart directly by using@cart_object.books, even though the two classes donít have a direct relationship. Without using the new:through option, we would need to laboriously go through theCartItemclass:@cart_object.cart_items.map {|ci| ci.book }.

Next, we populate theCreateCartItems migration that was created by thescript/generatecommand. Open006_create_cart_items.rband make it look like the following:

class CreateCartItems < ActiveRecord::Migration
  def self.up
   
create_table :cart_items do |t|
      t.column :book_id, :integer
      t.column :cart_id, :integer
      t.column :price, :float
      t.column :amount, :integer
      t.column :created_at, :datetime
   
end
  end

  def self.down
    drop_table :cart_items
  end
end

We can leave theCreateCarts migration file untouched, since the default content is fine for the moment. Run the migrations with therake db:migratecommand.

$ rake db:migrate

--------------------------------------------
(in /home/george/projects/emporium)
== CreateCarts: migrating ===================================================== -- create_table(:carts)
  
-> 0.1681s
== CreateCarts: migrated (0.1685s) ============================================

== CreateCartItems: migrating ================================================= -- create_table(:cart_items)
   -> 0.0778s
== CreateCartItems: migrated (0.0781s) ========================================
--------------------------------------------


blog comments powered by Disqus
RUBY-ON-RAILS ARTICLES

- Ruby-on-Rails Faces Second Security Flaw in ...
- Ruby 2.0 Prepped for February 2013 Release
- Why LinkedIn Switched from Ruby on Rails
- Adding Style with Action Pack
- Handling HTML in Templates with Action Pack
- Filters, Controllers and Helpers in Action P...
- Action Pack and Controller Filters
- Action Pack Categories and Events
- Logging Out, Events and Templates with Actio...
- Action Pack Sessions and Architecture
- More on Action Pack Partial Templates
- Action Pack Partial Templates
- Displaying Error Messages with the Action Pa...
- Action Pack Request Parameters
- Creating an Action Pack Registration Form

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials