0

这些是我的 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  

购物车.rb

class Cart < ActiveRecord::Base

  has_many :items, dependent: :destroy
end  

项目.rb

class Item < ActiveRecord::Base


attr_accessible :cart_id, :product_id,:product

  belongs_to :cart
  belongs_to :product
end  

项目控制器

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:NilClass 的未定义方法“items”

这里有什么问题?
我正在关注示例Agile Web Development with Rails书。

4

2 回答 2

1

在您从 ItemController 的创建操作重定向到 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 
于 2013-07-30T17:04:49.533 回答
1

您正在重定向到clothes_path( redirect_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
于 2013-07-30T17:13:29.270 回答