These are my pruduct.rb, cart.eb and item.rb
class Product < ActiveRecord::Base
attr_accessible :category_id, :color, :description, :price, :size, :title, :product_type, :sub_category_id, :image_url
belongs_to :category
belongs_to :sub_category
has_many :items
end
Cart.rb
class Cart < ActiveRecord::Base
has_many :items, dependent: :destroy
end
Item.rb
class Item < ActiveRecord::Base
attr_accessible :cart_id, :product_id,:product
belongs_to :cart
belongs_to :product
end
The ItemContoller
class ItemController < ApplicationController
def create
@cart=current_cart
product=Product.find(params[:product_id])
@item=@cart.items.build(product: product)
redirect_to clothes_path
flash.now[:success]="Product successfully added to Cart"
end
end
Now in my views when I want to show the cart contents like
<%= @cart.items.each do |item| %>
The current_cart method
def current_cart
cart=Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
cart=Cart.create
session[:cart_id]=cart.id
cart
end
it gives me this error
undefined method `items' for nil:NilClass
What is wrong here?
I'm following the example Agile web Developement with Rails book.