Agile Web Development with Rails, Edition 5

11.2 Iteration F2: Creating an AJAX-Based Cart 10.4 Playtime

11.1 Iteration F1: Moving the Cart

Refactor the cart view into partials, and reference the result from the layout.

Create a "partial" view, for just one line item

edit app/views/line_items/_line_item.html.erb
<tr>
  <td><%= line_item.quantity %>&times;</td>
  <td><%= line_item.product.title %></td>
  <td class="item_price"><%= number_to_currency(line_item.total_price) %></td>
</tr>

Replace that portion of the view with a callout to the partial

edit app/views/carts/show.html.erb
<p id="notice"><%= notice %></p>
 
<h2>Your Cart</h2>
<table>
  <%= render(@cart.line_items) %>
 
  <tr class="total_line">
    <td colspan="2">Total</td>
    <td class="total_cell"><%= number_to_currency(@cart.total_price) %></td>
  </tr>
 
</table>
 
<%= button_to 'Empty cart', @cart, method: :delete,
    data: { confirm: 'Are you sure?' } %>

Make a copy as a partial for the cart controller

cp app/views/carts/show.html.erb app/views/carts/_cart.html.erb

Modify the copy to reference the (sub)partial and take input from @cart

edit app/views/carts/_cart.html.erb
<h2>Your Cart</h2>
<table>
  <%= render(cart.line_items) %>
 
  <tr class="total_line">
    <td colspan="2">Total</td>
    <td class="total_cell"><%= number_to_currency(cart.total_price) %></td>
  </tr>
 
</table>
 
<%= button_to 'Empty cart', cart, method: :delete,
    data: { confirm: 'Are you sure?' } %>

Keep things DRY

edit app/views/carts/show.html.erb
<p id="notice"><%= notice %></p>
 
<%= render @cart %>

Reference the partial from the layout.

edit app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
  <head>
    <title>Pragprog Books Online Store</title>
    <%= csrf_meta_tags %>
 
    <%= csrf_meta_tags %>
 
    <%= stylesheet_link_tag    'application', media: 'all',
    'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>
 
  <body class="<%= controller.controller_name %>">
    <div id="banner">
      <%= image_tag 'logo.svg', alt: 'The Pragmatic Bookshelf' %>
      <span class="title"><%= @page_title %></span>
    </div>
    <div id="columns">
      <div id="side">
        <div id="cart">
          <%= render @cart %>
        </div>
 
        <ul>
          <li><a href="http://www....">Home</a></li>
          <li><a href="http://www..../faq">Questions</a></li>
          <li><a href="http://www..../news">News</a></li>
          <li><a href="http://www..../contact">Contact</a></li>
        </ul>
      </div>
      <div id="main">
        <%= yield %>
      </div>
    </div>
  </body>
</html>

Insert a call in the controller to find the cart

edit app/controllers/store_controller.rb
class StoreController < ApplicationController
  include CurrentCart
  before_action :set_cart
  def index
    @products = Product.order(:title)
  end
end

Add a small bit of style.

edit app/assets/stylesheets/carts.scss
// Place all the styles related to the Carts controller here.
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/
 
.carts, #side #cart {
  .item_price, .total_line {
    text-align: right;
  }
 
  .total_line .total_cell {
    font-weight: bold;
    border-top: 1px solid #595;
  }
}
edit app/assets/stylesheets/application.scss
  #side {
    padding: 1em 2em;
    background: #141;
 
    form, div {
      display: inline;
    }  
 
    input {
      font-size: small;
    }
 
    #cart {
      font-size: smaller;
      color:     white;
 
      table {
        border-top:    1px dotted #595;
        border-bottom: 1px dotted #595;
        margin-bottom: 10px;
      }
    }
 
    ul {
      padding: 0;
 
      li {
        list-style: none;
 
        a {
          color: #bfb;
          font-size: small;
        }
      }
    }
  }

Change the redirect to be back to the store.

edit app/controllers/line_items_controller.rb
  def create
    product = Product.find(params[:product_id])
    @line_item = @cart.add_product(product)
 
    respond_to do |format|
      if @line_item.save
        format.html { redirect_to store_index_url }
        format.json { render :show,
          status: :created, location: @line_item }
      else
        format.html { render :new }
        format.json { render json: @line_item.errors,
          status: :unprocessable_entity }
      end
    end
  end

Purchase another product.

get /

Your Cart

Rails, Angular, Postgres, and Bootstrap $90.00
Seven Mobile Apps in Seven Weeks $26.00
Total $116.00

Your Pragmatic Catalog

Dcbang

Rails, Angular, Postgres, and Bootstrap

Powerful, Effective, and Efficient Full-Stack Web Development As a Rails developer, you care about user experience and performance, but you also want simple and maintainable code. Achieve all that by embracing the full stack of web development, from styling with Bootstrap, building an interactive user interface with AngularJS, to storing data quickly and reliably in PostgreSQL. Take a holistic view of full-stack development to create usable, high-performing applications, and learn to use these technologies effectively in a Ruby on Rails environment.

$45.00
Adrpo

Ruby Performance Optimization

Why Ruby Is Slow, and How to Fix It You don’t have to accept slow Ruby or Rails performance. In this comprehensive guide to Ruby optimization, you’ll learn how to write faster Ruby code—but that’s just the beginning. See exactly what makes Ruby and Rails code slow, and how to fix it. Alex Dymo will guide you through perils of memory and CPU optimization, profiling, measuring, performance testing, garbage collection, and tuning. You’ll find that all those “hard” things aren’t so difficult after all, and your code will run orders of magnitude faster.

$46.00
7apps

Seven Mobile Apps in Seven Weeks

Native Apps, Multiple Platforms Answer the question “Can we build this for ALL the devices?” with a resounding YES. This book will help you get there with a real-world introduction to seven platforms, whether you’re new to mobile or an experienced developer needing to expand your options. Plus, you’ll find out which cross-platform solution makes the most sense for your needs.

$26.00
post /line_items?product_id=3
You are being redirected.
get http://localhost:3000/

Your Cart

Rails, Angular, Postgres, and Bootstrap $90.00
Seven Mobile Apps in Seven Weeks $52.00
Total $142.00

Your Pragmatic Catalog

Dcbang

Rails, Angular, Postgres, and Bootstrap

Powerful, Effective, and Efficient Full-Stack Web Development As a Rails developer, you care about user experience and performance, but you also want simple and maintainable code. Achieve all that by embracing the full stack of web development, from styling with Bootstrap, building an interactive user interface with AngularJS, to storing data quickly and reliably in PostgreSQL. Take a holistic view of full-stack development to create usable, high-performing applications, and learn to use these technologies effectively in a Ruby on Rails environment.

$45.00
Adrpo

Ruby Performance Optimization

Why Ruby Is Slow, and How to Fix It You don’t have to accept slow Ruby or Rails performance. In this comprehensive guide to Ruby optimization, you’ll learn how to write faster Ruby code—but that’s just the beginning. See exactly what makes Ruby and Rails code slow, and how to fix it. Alex Dymo will guide you through perils of memory and CPU optimization, profiling, measuring, performance testing, garbage collection, and tuning. You’ll find that all those “hard” things aren’t so difficult after all, and your code will run orders of magnitude faster.

$46.00
7apps

Seven Mobile Apps in Seven Weeks

Native Apps, Multiple Platforms Answer the question “Can we build this for ALL the devices?” with a resounding YES. This book will help you get there with a real-world introduction to seven platforms, whether you’re new to mobile or an experienced developer needing to expand your options. Plus, you’ll find out which cross-platform solution makes the most sense for your needs.

$26.00

Run tests... oops.

rails test
Run options: --seed 23951
 
# Running:
 
..E
 
Error:
ProductsControllerTest#test_should_get_index:
ActionView::Template::Error: 'nil' is not an ActiveModel-compatible object. It must implement :to_partial_path.
    app/views/layouts/application.html.erb:25:in `_app_views_layouts_application_html_erb__4393098129047445701_60668620'
    test/controllers/products_controller_test.rb:18:in `block in <class:ProductsControllerTest>'
 
bin/rails test test/controllers/products_controller_test.rb:17
 
.E
 
Error:
ProductsControllerTest#test_should_get_edit:
ActionView::Template::Error: 'nil' is not an ActiveModel-compatible object. It must implement :to_partial_path.
    app/views/layouts/application.html.erb:25:in `_app_views_layouts_application_html_erb__4393098129047445701_64075500'
    test/controllers/products_controller_test.rb:43:in `block in <class:ProductsControllerTest>'
 
bin/rails test test/controllers/products_controller_test.rb:42
 
E
 
Error:
ProductsControllerTest#test_should_show_product:
ActionView::Template::Error: 'nil' is not an ActiveModel-compatible object. It must implement :to_partial_path.
    app/views/layouts/application.html.erb:25:in `_app_views_layouts_application_html_erb__4393098129047445701_66086680'
    test/controllers/products_controller_test.rb:38:in `block in <class:ProductsControllerTest>'
 
bin/rails test test/controllers/products_controller_test.rb:37
 
..E
 
Error:
ProductsControllerTest#test_should_get_new:
ActionView::Template::Error: 'nil' is not an ActiveModel-compatible object. It must implement :to_partial_path.
    app/views/layouts/application.html.erb:25:in `_app_views_layouts_application_html_erb__4393098129047445701_66423400'
    test/controllers/products_controller_test.rb:23:in `block in <class:ProductsControllerTest>'
 
bin/rails test test/controllers/products_controller_test.rb:22
 
.........E
 
Error:
LineItemsControllerTest#test_should_get_index:
ActionView::Template::Error: 'nil' is not an ActiveModel-compatible object. It must implement :to_partial_path.
    app/views/layouts/application.html.erb:25:in `_app_views_layouts_application_html_erb__4393098129047445701_63214280'
    test/controllers/line_items_controller_test.rb:9:in `block in <class:LineItemsControllerTest>'
 
bin/rails test test/controllers/line_items_controller_test.rb:8
 
E
 
Error:
LineItemsControllerTest#test_should_show_line_item:
ActionView::Template::Error: 'nil' is not an ActiveModel-compatible object. It must implement :to_partial_path.
    app/views/layouts/application.html.erb:25:in `_app_views_layouts_application_html_erb__4393098129047445701_64316540'
    test/controllers/line_items_controller_test.rb:38:in `block in <class:LineItemsControllerTest>'
 
bin/rails test test/controllers/line_items_controller_test.rb:37
 
E
 
Error:
LineItemsControllerTest#test_should_get_new:
ActionView::Template::Error: 'nil' is not an ActiveModel-compatible object. It must implement :to_partial_path.
    app/views/layouts/application.html.erb:25:in `_app_views_layouts_application_html_erb__4393098129047445701_64400000'
    test/controllers/line_items_controller_test.rb:14:in `block in <class:LineItemsControllerTest>'
 
bin/rails test test/controllers/line_items_controller_test.rb:13
 
E
 
Error:
LineItemsControllerTest#test_should_get_edit:
ActionView::Template::Error: 'nil' is not an ActiveModel-compatible object. It must implement :to_partial_path.
    app/views/layouts/application.html.erb:25:in `_app_views_layouts_application_html_erb__4393098129047445701_67723720'
    test/controllers/line_items_controller_test.rb:43:in `block in <class:LineItemsControllerTest>'
 
bin/rails test test/controllers/line_items_controller_test.rb:42
 
.....E
 
Error:
CartsControllerTest#test_should_get_index:
ActionView::Template::Error: 'nil' is not an ActiveModel-compatible object. It must implement :to_partial_path.
    app/views/layouts/application.html.erb:25:in `_app_views_layouts_application_html_erb__4393098129047445701_61326980'
    test/controllers/carts_controller_test.rb:9:in `block in <class:CartsControllerTest>'
 
bin/rails test test/controllers/carts_controller_test.rb:8
 
..
 
Finished in 0.831117s, 36.0960 runs/s, 64.9728 assertions/s.
 
30 runs, 54 assertions, 0 failures, 9 errors, 0 skips

Verify that the products page is indeed broken

get /products

HTTP Response Code: 500

ArgumentError in Products#index

Showing /home/rubys/git/awdwr/edition4/work-233-50/depot/app/views/layouts/application.html.erb where line #25 raised:

'nil' is not an ActiveModel-compatible object. It must implement :to_partial_path.
Extracted source (around line #25):
23
24
25
26
27
28
              
<!-- START_HIGHLIGHT -->
<div id="cart">
<%= render @cart %>
</div>
<!-- END_HIGHLIGHT -->

Rails.root: /home/rubys/git/awdwr/edition4/work-233-50/depot

Application Trace | Framework Trace | Full Trace

Request

Parameters:

None

Response

Headers:

None

Check for nil

edit app/views/layouts/application.html.erb
      <div id="side">
        <div id="cart">
          <% if @cart %>
            <%= render @cart %>
          <% end %>
        </div>
 
        <ul>
          <li><a href="http://www....">Home</a></li>
          <li><a href="http://www..../faq">Questions</a></li>
          <li><a href="http://www..../news">News</a></li>
          <li><a href="http://www..../contact">Contact</a></li>
        </ul>
      </div>

all better

rails test
Run options: --seed 41562
 
# Running:
 
..............................
 
Finished in 0.764232s, 39.2551 runs/s, 82.4357 assertions/s.
 
30 runs, 63 assertions, 0 failures, 0 errors, 0 skips

11.2 Iteration F2: Creating an AJAX-Based Cart 10.4 Playtime