The Depot Application

The Depot Application

8.4 Iteration C3: Handling Errors 8.2 Iteration C1: Creating a Cart

8.3 Iteration C2: Creating a Smarter Cart

edit app/models/cart_item.rb
class CartItem
 
  attr_reader :product, :quantity
  
  def initialize(product)
    @product = product
    @quantity = 1
  end
  
  def increment_quantity
    @quantity += 1
  end
  
  def title
    @product.title
  end
  
  def price
    @product.price * @quantity
  end
end
edit app/models/cart.rb
  def add_product(product)
    current_item = @items.find {|item| item.product == product}
    if current_item
      current_item.increment_quantity
    else
      @items << CartItem.new(product)
    end
  end
edit app/views/store/add_to_cart.html.erb
<h2>Your Pragmatic Cart</h2>
<ul>
  <% for item in @cart.items %>
    <li><%= item.quantity %> &times; <%= item.title %></li>
  <% end %>
</ul>
get /store/add_to_cart/2

NoMethodError in StoreController#add_to_cart

undefined method `product' for #<Product:0x7f418484c188>

Rails.root: /home/rubys/git/awdwr/edition3/work-30/depot

Application Trace | Framework Trace | Full Trace
app/models/cart.rb:10:in `add_product'
app/models/cart.rb:10:in `each'
app/models/cart.rb:10:in `find'
app/models/cart.rb:10:in `add_product'
app/controllers/store_controller.rb:11:in `add_to_cart'

Request

Parameters:

{"id"=>"2"}

Show session dump

Show env dump

Response

Headers:

None

rake db:sessions:clear
get /store/add_to_cart/2

Your Pragmatic Cart

  • 1 × Pragmatic Project Automation
get /store/add_to_cart/2

Your Pragmatic Cart

  • 2 × Pragmatic Project Automation
get /store/add_to_cart/3

Your Pragmatic Cart

  • 2 × Pragmatic Project Automation
  • 1 × Pragmatic Version Control
get /store/add_to_cart/wibble

ActiveRecord::RecordNotFound in StoreController#add_to_cart

Couldn't find Product with ID=wibble

Rails.root: /home/rubys/git/awdwr/edition3/work-30/depot

Application Trace | Framework Trace | Full Trace
app/controllers/store_controller.rb:9:in `add_to_cart'

Request

Parameters:

{"id"=>"wibble"}

Show session dump

Show env dump

Response

Headers:

None

8.4 Iteration C3: Handling Errors 8.2 Iteration C1: Creating a Cart