9.2 Iteration D2: Connecting Products to Carts 8.6 Playtime
Create a cart. Put it in a session. Find it.
Create a cart.
rails generate scaffold Cart
invoke active_record
create db/migrate/20140204194949_create_carts.rb
create app/models/cart.rb
invoke test_unit
create test/unit/cart_test.rb
create test/fixtures/carts.yml
route resources :carts
invoke scaffold_controller
create app/controllers/carts_controller.rb
invoke erb
create app/views/carts
create app/views/carts/index.html.erb
create app/views/carts/edit.html.erb
create app/views/carts/show.html.erb
create app/views/carts/new.html.erb
create app/views/carts/_form.html.erb
invoke test_unit
create test/functional/carts_controller_test.rb
invoke helper
create app/helpers/carts_helper.rb
invoke test_unit
create test/unit/helpers/carts_helper_test.rb
invoke stylesheets
identical public/stylesheets/scaffold.css
rake db:migrate
mv 20140204194949_create_carts.rb 20140204000002_create_carts.rb
== CreateCarts: migrating ====================================================
-- create_table(:carts)
-> 0.0007s
== CreateCarts: migrated (0.0008s) ===========================================
Implement set_cart, which creates a new cart if it can't find one.
edit app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
private
def set_cart
@cart = Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
@cart = Cart.create
session[:cart_id] = @cart.id
end
end