Home arrow Ruby-on-Rails arrow Page 6 - Finishing a Shopping Cart Implementation

Finishing a Shopping Cart Implementation

In this second part of a two-part series on implementing a shopping cart for an online bookstore, we'll create a floating cart that will show its contents to the user, and set up its capabilities. This article 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 / 11
June 04, 2010
  1. · Finishing a Shopping Cart Implementation
  2. · Implementing the Add Items to the Cart User Story
  3. · Ajax’ing It
  4. · Drag-and-Drop
  5. · Implementing the Remove Items from the Cart User Story
  6. · Implementing the Clear the Cart User Story

print this article

Finishing a Shopping Cart Implementation - Implementing the Clear the Cart User Story
(Page 6 of 6 )

Clearing the cart follows pretty much the same path as the two previous user stories. We first add two functional tests to test/functional/cart_controller_test.rb, to test clearing the cart with both a normalPOSTrequest and anXmlHttpRequest.  

def test_clearing
    post :add, :id => 4
    assert_equal [Book.find(4)], Cart.find(@request.session[:cart_id]).books

    post :clear
    assert_response :redirect
    assert_redirected_to :controller => "catalog"
    assert_equal [], Cart.find(@request.session[:cart_id]).books

  def test_clearing_with_xhr
    post :add, :id => 4
    assert_equal [Book.find(4)], Cart.find(@request.session[:cart_id]).books

    xhr :post, :clear
    assert_response :success
    assert_equal 0, Cart.find(@request.session[:cart_id]).cart_items.size

Then we add a new action calledclear toapp/controllers/cart_controller.rb, following along the lines of theaddandremove actions.

def clear
if request.xhr?
    flash.now[:cart_notice] = "Cleared the cart"
    render :action => "clear_with_ajax"
  elsif request.post?
    flash[:cart_notice] = "Cleared the cart"
    redirect_to :controller => "catalog"

Next, we add the view for the non-Ajax way of clearing the cart,cart/clear.rhtml.

<strong>Please confirm clearing your shopping cart.</strong>
<%= button_to "Confirm", :action => "clear" %>

Then we move on to implement thecart/clear_with_ajax.rjstemplate.

page.replace_html "shopping_cart", :partial => "cart/cart"
page.visual_effect :fade, 'cart_notice', :duration => 3

All that the template does is to replace the whole shopping cart with a new, empty one, rendered by thecart/_cart.rhtmlpartial. Note that since we’re re-rendering the wholeshopping_cartelement with a partial, we don’t need to explicitly show thecart_notificationdivision (as we did with theremove_with_ajaxtemplate), because it’s already part of the_cart.rhtmlpartial template.

We’ll also add a link for clearing the cart to the cart partial, but only if the cart is not empty. Remember that we created theclear_cart_linkhelper earlier in this chapter (see Listing 5-3).

<% if flash[:cart_notice] %>
  <%= render :partial => "cart/cart_notice" %>
<% end %>

  <h3>Your Shopping Cart</h3>

    <% for item in @cart.cart_items %>
    <li id="cart_item_<%= item.book.id %>">
      <%= render :partial => "cart/item", :object => item %>
    <% end %>
  <p id="cart_total"><strong>Total: $<%= @cart.total %></strong></p>
  <% unless @cart.cart_items.empty? %>
  <p id="clear_cart_link">
    <%= clear_cart_link %>
  <% end %>

Our application can now be used to add items to the shopping cart, remove them from it, and clear the whole cart with a single click.

The next natural step would be to implement the functionality of checking out—that is, finalizing the order. However, since the checkout is such a beast with credit card processing and all, we’ll postpone that for now and give you all the gory details in Chapter 9.


In this chapter, we implemented a shopping cart for an online store. We used the Ajax capabilities in Ruby on Rails to implement a fast and interactive, but also backward-compatible shopping cart.

In the course of implementing the shopping cart, we showed you how to use thehas_many :throughassociation join models with ActiveRecord classes and how to use the Rails controller filters and store information in thesessionhash. You saw how to put Rails helpers likepluralizeto use and how to write your own link helpers.

Our Ajax implementation demonstrated using the script.aculo.us JavaScript library, which is bundled with Rails, to create modern, Ajax-driven shopping carts. You also saw how to make sure your Ajax-driven site is also accessible to users whose browsers don’t support JavaScript. Also, we covered using the Rails .rjs templates to update multiple items inside a web page with a single Ajax call.  

DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus

- 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 

Developer Shed Affiliates


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