mardi 22 octobre 2019

How to solve a problem when clicking the shopcart. Couldn't find LineItem with 'id'=2

I'm making a Ecommerce site with rails. when I try to click the add to cart link this error appears. I really appreciate it if you could give me a hint to solve this problem. Sorry for the long codes.

Error message

ActiveRecord::RecordNotFound at /line_items/2
Couldn't find LineItem with 'id'=2

line_items.controller

class LineItemsController < ApplicationController
 include CurrentCart
 before_action :set_line_item, only: [:show, :edit, :update, :destroy]
 before_action :set_cart, only: [:create]


 def index
   @line_items = LineItem.all
 end

 def show
 end

 def new
   @line_item = LineItem.new
 end

 def edit
 end

  def create
   item = Item.find(params[:item_id])
   @line_item = @cart.add_item(item)

   respond_to do |format|
     if @line_item.save
       format.html { redirect_to @line_item.cart, notice: 'カゴに追加されました' }
       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

 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


 def destroy
   @cart = Cart.find(session[:cart_id])
   @line_item.destroy
   respond_to do |format|
     format.html { redirect_to cart_path(@cart), notice: 'Line item was successfully destroyed.' }
     format.json { head :no_content }
   end
 end

 private
   def set_line_item     #it says I have a problem here
     @line_item = LineItem.find(params[:id])
   end

   def line_item_params
     params.require(:line_item).permit(:item_id)
   end
end

current_cart.rb

module CurrentCart
  private
  def set_cart
    @cart = Cart.find(session[:cart_id])
  rescue ActiveRecord::RecoedNotFound
    @cart = Cart.create
    session[:cart_id] = @cart.id
  end
end

application.controller

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  include CurrentCart
  before_action :set_cart

end

routes

Rails.application.routes.draw do
  resources :line_items
  resources :carts
  resources :items
  devise_for :users, controllers:{
  registrations: 'registrations'
  }
  root 'items#index'
  devise_scope :user do
    get '/users/sign_out' => 'devise/sessions#destroy'
  end
end

I added "include CurrentCart, before_action :set_cart" to my application.controller but nothing changed. no problem with my linktag too.in my show.html.rb




Aucun commentaire:

Enregistrer un commentaire