Agile Web Development with Rails, Edition 4

9.2 Iteration D2: Connecting Products to Carts 8.6 Playtime

9.1 Iteration D1: Finding a Cart

Create a cart. Put it in a session. Find it.

Create a cart.

rails generate scaffold Cart
      invoke  active_record
      create    db/migrate/20170602134059_create_carts.rb
      create    app/models/cart.rb
      invoke    test_unit
      create      test/models/cart_test.rb
      create      test/fixtures/carts.yml
      invoke  resource_route
       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/controllers/carts_controller_test.rb
      invoke    helper
      create      app/helpers/carts_helper.rb
      invoke      test_unit
      invoke    jbuilder
      create      app/views/carts/index.json.jbuilder
      create      app/views/carts/show.json.jbuilder
      create      app/views/carts/_cart.json.jbuilder
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/carts.coffee
      invoke    scss
      create      app/assets/stylesheets/carts.scss
      invoke  scss
   identical    app/assets/stylesheets/scaffolds.scss
rake db:migrate
mv 20170602134059_create_carts.rb 20170602000002_create_carts.rb
== 20170602000002 CreateCarts: migrating ======================================
-- create_table(:carts)
   -> 0.0007s
== 20170602000002 CreateCarts: migrated (0.0008s) =============================
 

Implement set_cart, which creates a new cart if it can't find one.

edit app/controllers/concerns/current_cart.rb
module CurrentCart
 
  private
 
    def set_cart 
      @cart = Cart.find(session[:cart_id])
    rescue ActiveRecord::RecordNotFound
      @cart = Cart.create
      session[:cart_id] = @cart.id
    end
end

9.2 Iteration D2: Connecting Products to Carts 8.6 Playtime