简体   繁体   中英

Rails: ActiveRecord::RecordNotFound in Cart

I user friendly_id for all the items. I am getting an error in the cart.rb model saying .. Couldn't find Product with 'id'=the-pen

I'm unsure what to do. Any help would be appreciated

cart.rb

class CartItem < ActiveRecord::Base
    attr_reader :product_id, :quantity

    def initialize product_id, quantity = 1
        @product_id = product_id
        @quantity = quantity
    end

    def increment
        @quantity = @quantity + 1
    end

    def product
        Product.find product_id
    end

    def total_price
        product.price * quantity    
    end


end

ApplicationController.rb

def initialize_cart
    @cart = Cart.build_from_hash session
end

OrderForm.rb

def build_order_items
    @cart.items.each do |item|
        @order.order_items.create! product_id: item.product_id, quantity: item.quantity
    end

Your CartItem's product method still uses the .find method by itself, which may be throwing the error as you're inputting a string as an argument instead of the numeric ID. Try modifying it to use .friendly.find instead.

Hope this helps!

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