nil的未定义方法`items':@ cart.items.each中的NilClass

时间:2013-07-30 16:57:33

标签: ruby-on-rails nomethoderror

这些是我的 pruduct.rb,cart.eb和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  

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  

现在,在我的视图中,当我想要显示购物车内容

<%= @cart.items.each do |item| %>  

current_cart 方法

def current_cart
cart=Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
    cart=Cart.create
    session[:cart_id]=cart.id
    cart
  end

它给了我这个错误

  

nil的未定义方法`items':NilClass

这里有什么问题?
我正在关注使用Rails的敏捷Web开发一书。

2 个答案:

答案 0 :(得分:1)

从ItemController的create action重定向到cloths_path后,@cart实例变量将无法用于布料的控制器索引操作。需要重置一些如何在索引操作中

for eg: - 

you can pass cart id to it and find it in index cloth's action

redirect_to clothes_path, card_id: @cart.id

and in cloth's index action do 

@cart = Cart.find params[:cart_id]


create a mathod in application controller, and after u create a new cart, save its id in session, like

session[:cart] = @cart.id

def current_cart
  @cart = Cart.find session[:cart_id]
end

and in view use current_cart method instead of @cart 

答案 1 :(得分:1)

您正在重定向到clothes_pathredirect_to clothes_path),而您似乎有ClothController。此控制器应包含index方法来呈现索引页。将current_cart分配给@cart

class ClothController < ApplicationController

  def index
    @cart = current_cart
  end

  ...

end

<强>更新

要在@cart控制器的所有视图中提供Cloth,可以使用before_filter方法设置@cart变量。您可以在所需的控制器中添加此定义。有关详细信息,请访问http://guides.rubyonrails.org/action_controller_overview.html#filters

class ClothController < ApplicationController
  before_filter :set_current_cart

  def index
  end

  ...

  private

  def set_current_cart
    @cart = current_cart
  end

end

current_cart方法应该作为帮助程序实现,以便在所有控制器中可用。 (http://guides.rubyonrails.org/form_helpers.html


更新2

/app/helpers/cart_helper.rb中实施帮助:

module CartHelper

  def current_cart
    # Your current cart method code
  end

end

并将其包含在所需的控制器中。 current_cart方法将在包含CartHelper的控制器的所有视图中可用。

class ClothController < ApplicationController
  include CartHelper

  ...
end