Agile Web Development with Rails, Edition 5

9.4 Playtime 9.2 Iteration D2: Connecting Products to Carts

9.3 Iteration D3: Adding a button

Now we connect the model objects we created to the controller and the view.

Add the button, connecting it to the Line Item Controller, passing the product id.

edit app/views/store/index.html.erb
<% if notice %>
  <aside id="notice"><%= notice %></aside>
<% end %>
 
<h1>Your Pragmatic Catalog</h1>
 
<ul class="catalog">
  <% cache @products do %>
    <% @products.each do |product| %>
      <% cache product do %>
        <li>
          <%= image_tag(product.image_url) %>
          <h2><%= product.title %></h2>
          <p>
            <%= sanitize(product.description) %>
          </p>
          <div class="price">
            <%= number_to_currency(product.price) %>
            <%= button_to 'Add to Cart', line_items_path(product_id: product) %>
          </div>
        </li>
      <% end %>
    <% end %>
  <% end %>
</ul>

Add a bit of style to make it show all on one line

edit app/assets/stylesheets/store.scss
      .price {
        font-size: 1.414em;
      }
 
      form, div {
        display: inline;
      }
      input[type="submit"] {
        background-color: #282;
        border-radius: 0.354em;
        border: solid thin #141;
        color: white;
        font-size: 1em;
        padding: 0.354em 1em;
      }
      input[type="submit"]:hover {
        background-color: #141;
      } 
    }

See the button on the page

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

Update the LineItem.new call to use set_cart and the product id. Additionally change the logic so that redirection upon success goes to the cart instead of the line item.

edit app/controllers/line_items_controller.rb
class LineItemsController < ApplicationController
  include CurrentCart
  before_action :set_cart, only: [:create]
  before_action :set_line_item, only: [:show, :edit, :update, :destroy]
 
  # GET /line_items
  #...
end
edit app/controllers/line_items_controller.rb
  def create
    product = Product.find(params[:product_id])
    @line_item = @cart.line_items.build(product: product)
 
    respond_to do |format|
      if @line_item.save
        format.html { redirect_to @line_item.cart,
          notice: 'Line item was successfully created.' }
        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

Try it once, and see that the output isn't very useful yet.

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

Line item was successfully created.

Edit | Back

Update the template that shows the Cart.

edit app/views/carts/show.html.erb
<% if notice %>
  <aside id="notice"><%= notice %></aside>
<% end %>
 
<h2>Your Pragmatic Cart</h2>
<ul>    
  <% @cart.line_items.each do |item| %>
    <li><%= item.product.title %></li>
  <% end %>
</ul>

Style the flash

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
    }
    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;
  }
}

Try it once again, and see that the products in the cart.

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

Your Pragmatic Cart

  • Seven Mobile Apps in Seven Weeks
  • Seven Mobile Apps in Seven Weeks

9.4 Playtime 9.2 Iteration D2: Connecting Products to Carts