简体   繁体   中英

ActiveRecord::RecordNotFound “Couldn't find Cart with 'id'=”

Was playing around with this today and received this error I am trying to find a way around. I am trying to have it so a cart will be created when a user signs into his/her account. The error is coming from my sessions controller at the create action

Sessions Controller

class SessionsController < ApplicationController


  def create
    ....

    if @user && @user.authenticate(params[:user][:password])
        session[:user_id] = @user.id
        @cart = Cart.create(:cart => Cart.find(params[:id]))
        @user.cart = @cart.id
        @user.save
          redirect_to @user

specifically it is coming from the line

@cart = Cart.create(:cart => Cart.find(params[:id]) )

If anyone has an idea how to fix this please let me know.

I think you'd be better off with something like:

@cart = Cart.find_by_id(params[:id]) || @cart = Cart.create(:cart => params[:id])

find_by_id won't throw an exception if record is not found.

You can't find the cart before you create it. And if you have an id for cart, you don't actually need to create it at all, just find it and set the user's cart_id to that value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM