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 LineItemsController < ApplicationController
- include CurrentCart
- before_action :set_cart, only: [:create]
- before_action :set_line_item, only: [:show, :edit, :update, :destroy]
- # GET /line_items
- # GET /line_items.json
- def index
- @line_items = LineItem.all
- end
- # GET /line_items/1
- # GET /line_items/1.json
- def show
- end
- # GET /line_items/new
- def new
- @line_item = LineItem.new
- end
- # GET /line_items/1/edit
- def edit
- end
- # POST /line_items
- # POST /line_items.json
- def create
- product = Product.find(params[:product_id])
- @line_item = @cart.line_items.build(product: product)
- respond_to do |format|
- if @line_item.save
- format.html { redirect_to @line_item.cart,
- notice: 'Line item was successfully created.' }
- format.json { render :show,
- status: :created, location: @line_item }
- else
- format.html { render :new }
- format.json { render json: @line_item.errors,
- status: :unprocessable_entity }
- end
- end
- end
- # PATCH/PUT /line_items/1
- # PATCH/PUT /line_items/1.json
- def update
- respond_to do |format|
- if @line_item.update(line_item_params)
- format.html { redirect_to @line_item, notice: 'Line item was successfully updated.' }
- format.json { render :show, status: :ok, location: @line_item }
- else
- format.html { render :edit }
- format.json { render json: @line_item.errors, status: :unprocessable_entity }
- end
- end
- end
- # DELETE /line_items/1
- # DELETE /line_items/1.json
- def destroy
- @line_item.destroy
- respond_to do |format|
- format.html { redirect_to line_items_url, notice: 'Line item was successfully destroyed.' }
- format.json { head :no_content }
- end
- end
- private
- # Use callbacks to share common setup or constraints between actions.
- def set_line_item
- @line_item = LineItem.find(params[:id])
- end
- # Never trust parameters from the scary internet, only allow the white list through.
- def line_item_params
- params.require(:line_item).permit(:product_id, :cart_id)
- end
- #...
- end
|