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 class="quantity"><%= line_item.quantity %></td>
  <td><%= line_item.product.title %></td>
  <td class="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
<article>
  <% if notice %>
    <aside id="notice"><%= notice %></aside>
  <% end %>
 
  <h2>Your Cart</h2>
  <table>
 
    <%= render(@cart.line_items) %>
    <tfoot>
      <tr>
        <th colspan="2">Total:</th>
        <td class="price"><%= number_to_currency(@cart.total_price) %></td>
      </tr>
    </tfoot>
  </table>
  <%= button_to 'Empty cart', @cart,
                method: :delete,
                data: { confirm: 'Are you sure?' } %>
 
</article>

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
<article>
  <% if notice %>
    <aside id="notice"><%= notice %></aside>
  <% end %>
 
  <h2>Your Cart</h2>
  <table>
 
    <%= render(cart.line_items) %>
    <tfoot>
      <tr>
        <th colspan="2">Total:</th>
        <td class="price"><%= number_to_currency(cart.total_price) %></td>
      </tr>
    </tfoot>
  </table>
  <%= button_to 'Empty cart', cart,
                method: :delete,
                data: { confirm: 'Are you sure?' } %>
 
</article>

Keep things DRY

edit app/views/carts/show.html.erb
<%= 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 %>
 
    <%= stylesheet_link_tag 'application', media: 'all',
                            'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application',
                               'data-turbolinks-track': 'reload' %>
  </head>
 
  <body>
    <header class="main">
      <%= image_tag 'logo.svg', alt: 'The Pragmatic Bookshelf' %>
      <h1><%= @page_title %></h1>
    </header>
    <section class="content">
      <nav class="side_nav">
        <div id="cart" class="carts">
          <%= render @cart %>
        </div>
        <ul>
          <li><a href="/">Home</a></li>
          <li><a href="/questions">Questions</a></li>
          <li><a href="/news">News</a></li>
          <li><a href="/contact">Contact</a></li>
        </ul>
      </nav>
			<main class='<%= controller.controller_name %>'>
        <%= yield %>
      </main>
    </section>
  </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/application.scss
/*
 * This is a manifest file that'll be compiled into application.css, which will
 * include all the files listed below.
 * 
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, or any
 * plugin's vendor/assets/stylesheets directory can be referenced here using a
 * relative path.
 * 
 * You're free to add application-wide styles to this file and they'll appear
 * at the bottom of the compiled file so the styles you add here take
 * precedence over styles defined in any other CSS/SCSS files in this
 * directory. Styles in this file should be added after the last require_*
 * statement. It is generally better to create a new file per style scope.
 * 
 *= require_tree .
 *= require_self
 */
 
body {
  margin: 0;
  padding: 0;
}
header.main {
  text-align: center; // center on mobile
  @media (min-width: 30em) {
    text-align: left; // left align on desktop
  }
  background: #282;
  margin: 0;
  h1 {
    display: none;
  }
}
 
.notice, #notice {
  background: #ffb;
  border-radius: 0.5em;
  border: solid 0.177em #882;
  color: #882;
  font-weight: bold;
  margin-bottom: 1em;
  padding: 1em 1.414em;
  text-align: center;
}
.content {
  margin: 0;
  padding: 0;
 
  display: flex;
  display: -webkit-flex;
  flex-direction: column; // mobile is horizontally laid out
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
 
  @media (min-width: 30em) {
    flex-direction: row;  // desktop is vertically laid out
    -webkit-box-orient: horizontal;
  }
 
  nav {
    padding-bottom: 1em;
    background: #141;
    text-align: center;  // mobile has centered nav
    @media (min-width: 30em) {
      text-align: left; // desktop nav is left-aligned
      padding: 1em;     // and needs more padding
    }
 
    #cart {
      article {
        h2 {
          margin-top: 0;
        }
        background: white;
        border-radius: 0.5em;
        margin: 1em;
        padding: 1.414em;
        @media (min-width: 30em) {
          margin: 0; // desktop doesn't need this margin
        }
      }
    }
    ul {
      list-style: none;
      margin: 0;
      padding: 0;
      @media (min-width: 30em) {
        padding-right: 1em; // give desktop some extra space
      }
      li {
        margin: 0;
        padding: 0.5em;
        text-transform: uppercase;
        letter-spacing: 0.354em;
        a {
          color: #bfb;
          text-decoration: none;
        }
        a:hover {
          background: none;
          color: white;
        }
      }
    }
  }
  main {
    padding: 0.5em;
  }
}

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 /
The Pragmatic Bookshelf

Your Pragmatic Catalog

  • 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
  • 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
  • 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/
The Pragmatic Bookshelf

Your Pragmatic Catalog

  • 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
  • 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
  • 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 33674
 
# Running:
 
.......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:24:in `_app_views_layouts_application_html_erb___2035715321172067450_38693600'
    test/controllers/carts_controller_test.rb:9:in `block in <class:CartsControllerTest>'
 
bin/rails test test/controllers/carts_controller_test.rb:8
 
.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:24:in `_app_views_layouts_application_html_erb___2035715321172067450_38693600'
    test/controllers/products_controller_test.rb:45:in `block in <class:ProductsControllerTest>'
 
bin/rails test test/controllers/products_controller_test.rb:44
 
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:24:in `_app_views_layouts_application_html_erb___2035715321172067450_38693600'
    test/controllers/products_controller_test.rb:50:in `block in <class:ProductsControllerTest>'
 
bin/rails test test/controllers/products_controller_test.rb:49
 
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:24:in `_app_views_layouts_application_html_erb___2035715321172067450_38693600'
    test/controllers/products_controller_test.rb:14:in `block in <class:ProductsControllerTest>'
 
bin/rails test test/controllers/products_controller_test.rb:13
 
....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:24:in `_app_views_layouts_application_html_erb___2035715321172067450_38693600'
    test/controllers/products_controller_test.rb:19:in `block in <class:ProductsControllerTest>'
 
bin/rails test test/controllers/products_controller_test.rb:18
 
.....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:24:in `_app_views_layouts_application_html_erb___2035715321172067450_38693600'
    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_index:
ActionView::Template::Error: 'nil' is not an ActiveModel-compatible object. It must implement :to_partial_path.
    app/views/layouts/application.html.erb:24:in `_app_views_layouts_application_html_erb___2035715321172067450_38693600'
    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:24:in `_app_views_layouts_application_html_erb___2035715321172067450_38693600'
    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_edit:
ActionView::Template::Error: 'nil' is not an ActiveModel-compatible object. It must implement :to_partial_path.
    app/views/layouts/application.html.erb:24:in `_app_views_layouts_application_html_erb___2035715321172067450_38693600'
    test/controllers/line_items_controller_test.rb:43:in `block in <class:LineItemsControllerTest>'
 
bin/rails test test/controllers/line_items_controller_test.rb:42
 
.
 
Finished in 0.496554s, 60.4163 runs/s, 108.7494 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/depot/app/views/layouts/application.html.erb where line #24 raised:

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

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

Application Trace | Framework Trace | Full Trace

Request

Parameters:

None

Response

Headers:

None

Clear highlights

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

Start side

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

End side

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

Add if statement

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

Add end statement

edit app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
  <head>
    <title>Pragprog Books Online Store</title>
    <%= csrf_meta_tags %>
 
    <%= stylesheet_link_tag 'application', media: 'all',
                            'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application',
                               'data-turbolinks-track': 'reload' %>
  </head>
 
  <body>
    <header class="main">
      <%= image_tag 'logo.svg', alt: 'The Pragmatic Bookshelf' %>
      <h1><%= @page_title %></h1>
    </header>
    <section class="content">
      <nav class="side_nav">
        <% if @cart %>
 
        <div id="cart" class="carts">
          <%= render @cart %>
        </div>
        <% end %>
 
        <ul>
          <li><a href="/">Home</a></li>
          <li><a href="/questions">Questions</a></li>
          <li><a href="/news">News</a></li>
          <li><a href="/contact">Contact</a></li>
        </ul>
      </nav>
      <main class='<%= controller.controller_name %>'>
        <%= yield %>
      </main>
    </section>
  </body>
</html>

all better

rails test
Run options: --seed 733
 
# Running:
 
..............................
 
Finished in 0.435370s, 68.9070 runs/s, 144.7046 assertions/s.
30 runs, 63 assertions, 0 failures, 0 errors, 0 skips

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