jeudi 28 mai 2015

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

CartsController.rb

class CartsController < ApplicationController
    before_filter :initialize_cart

    def add
        @cart.add_item params[:id]
        session["cart"] = @cart.serialize
        @product = Product.friendly.find(params[:id])
        redirect_to :back, notice: "Added #{@product.title} to cart"
    end

    def show
    end

    def checkout
        @order_form = OrderForm.new user: User.new
    end
end

ApplicationController.rb

def initialize_cart
    @cart = Cart.build_from_hash session
end

views/cart/show.html.erb

<% @cart.items.each do |item| %>
<%=link_to item.product.title, item.product %>
<%= item.quantity %>
<%= @cart.total_price %>

Aucun commentaire:

Enregistrer un commentaire