1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- #---
- # Excerpted from "Agile Web Development with Rails",
- # published by The Pragmatic Bookshelf.
- # Copyrights apply to this code. It may not be used to create training material,
- # courses, books, articles, and the like. Contact us if you are in doubt.
- # We make no guarantees that this code is fit for any purpose.
- # Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
- #---
- class CartsController < ApplicationController
- before_action :set_cart, only: [:show, :edit, :update, :destroy]
- rescue_from ActiveRecord::RecordNotFound, with: :invalid_cart
- # GET /carts
- # GET /carts.json
- def index
- @carts = Cart.all
- end
- # GET /carts/1
- # GET /carts/1.json
- def show
- end
- # GET /carts/new
- def new
- @cart = Cart.new
- end
- # GET /carts/1/edit
- def edit
- end
- # POST /carts
- # POST /carts.json
- def create
- @cart = Cart.new(cart_params)
- respond_to do |format|
- if @cart.save
- format.html { redirect_to @cart, notice: 'Cart was successfully created.' }
- format.json { render action: 'show', status: :created, location: @cart }
- else
- format.html { render action: 'new' }
- format.json { render json: @cart.errors, status: :unprocessable_entity }
- end
- end
- end
- # PATCH/PUT /carts/1
- # PATCH/PUT /carts/1.json
- def update
- respond_to do |format|
- if @cart.update(cart_params)
- format.html { redirect_to @cart, notice: 'Cart was successfully updated.' }
- format.json { head :no_content }
- else
- format.html { render action: 'edit' }
- format.json { render json: @cart.errors, status: :unprocessable_entity }
- end
- end
- end
- # DELETE /carts/1
- # DELETE /carts/1.json
- def destroy
- @cart.destroy if @cart.id == session[:cart_id]
- session[:cart_id] = nil
- respond_to do |format|
- format.html { redirect_to store_url }
- format.json { head :no_content }
- end
- end
- # ...
- private
- # ...
- def set_cart
- @cart = Cart.find(params[:id])
- end
- # Never trust parameters from the scary internet, only allow the white list through.
- def cart_params
- params[:cart]
- end
- def invalid_cart
- logger.error "Attempt to access invalid cart #{params[:id]}"
- redirect_to store_url, notice: 'Invalid cart'
- end
- end
|