smarter cart

Post on 18-Dec-2014

1.284 Views

Category:

Documents

6 Downloads

Preview:

Click to see full reader

DESCRIPTION

Chapter 10 1/8/2011

TRANSCRIPT

Creating a Smarter Cart

Jason Noblehttp://jasonnoble.org

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

Add Product Method

• app/models/cart.rb

Update Line Items Controller

• Change create method

Modify Cart Show View

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

Still have duplicates

Write a migration to fix existing carts

• rails generate migration combine_items_in_cart

Add an undo option

• Modify the migration self.down method

• rake db:rollback

Handling Errors

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

Add a message to the flash

• app/controllers/carts_controller.rb

Verify it works

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

Emptying your cart

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

Emptying your cart (cont.)

• app/controllers/carts_controller.rb

Run your tests often• rake test

• test/functional/carts_controller_test.rb

Better Cart View

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

Add total_price methods

• app/models/line_item.rb

• app/models/cart.rb

Make it prettier• public/stylesheets/depot.css

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

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.

top related