20
Creating a Smarter Cart Jason Noble http://jasonnoble.org

Smarter cart

Embed Size (px)

DESCRIPTION

Chapter 10 1/8/2011

Citation preview

Page 1: Smarter cart

Creating a Smarter Cart

Jason Noblehttp://jasonnoble.org

Page 2: Smarter cart

Adding a count to our cart

• rails generate migration add_quantity_to_line_item quantity:integer– Rails recognizes add_XXX_to_TABLE– Rails recognizes remove_XXX_to_TABLE

• Modify the migration to specify a default value– add_column :line_items, :quantity, :integer, :default => 1

Page 3: Smarter cart

Add Product Method

• app/models/cart.rb

Page 4: Smarter cart

Update Line Items Controller

• Change create method

Page 5: Smarter cart

Modify Cart Show View

• Add the quantity to the cart view• app/views/carts/show.html.erb

Page 6: Smarter cart

Still have duplicates

Page 7: Smarter cart

Write a migration to fix existing carts

• rails generate migration combine_items_in_cart

Page 8: Smarter cart

Add an undo option

• Modify the migration self.down method

• rake db:rollback

Page 9: Smarter cart

Handling Errors

Page 10: Smarter cart

Sending messages to the user

• Rails has a structure called flash• flash is a Hash that you can you can store stuff

in as you process a request• Contents of the flash are available to the next

request and then automatically deleted• Store error and debug messages in the flash to

help users understand what’s happening• flash is stored in the user’s session to make it

available between requests

Page 11: Smarter cart

Add a message to the flash

• app/controllers/carts_controller.rb

Page 12: Smarter cart

Verify it works

• http://localhost:3000/carts/wibble

Page 13: Smarter cart

Emptying your cart

• app/views/carts/show.html.erb

Page 14: Smarter cart

Emptying your cart (cont.)

• app/controllers/carts_controller.rb

Page 15: Smarter cart

Run your tests often• rake test

• test/functional/carts_controller_test.rb

Page 16: Smarter cart

Better Cart View

• app/views/carts/show.html.erb

Page 17: Smarter cart

Add total_price methods

• app/models/line_item.rb

• app/models/cart.rb

Page 18: Smarter cart

Make it prettier• public/stylesheets/depot.css

Page 19: Smarter cart

What we covered

• Adding/Removing a column to an existing table with a default value

• Migrating existing table data into new format• Providing flash notices to customer• Using the logger to log events• Deleted a record• Adjusted the way the cart is viewed, using CSS

Page 20: Smarter cart

Homework

• Create a migration that stores the product price in the line item table. Modify add_product method to capture the price.

• Add unit tests which add unique products and duplicate products.

• Use the flash functionality to show helpful messages

• Add the ability to delete individual line items from the cart. Bonus points to decrease quantity by 1.