NoMethodError - 未定义的方法`[]' for nil:NullClass在baskets控制器的破坏方法 - Rails

时间:2014-06-05 16:25:49

标签: ruby-on-rails ruby ruby-on-rails-4

我在一个篮子控制器中有一个destroy方法,它一直给我一个NoMethodError第44行,这是以下一行:

if basket.to_a.collect{|item| [item[:product_id], item[:size]]}.include? [prod.id, params[:basket][:size]]

create方法效果很好,所以我不确定destroy中的问题是什么?

baskets_controller.rb

class BasketsController < ApplicationController

def create
  prod = Product.find(params[:product_id])

  if basket.to_a.collect{|item| [item[:product_id], item[:size]]}.include? [prod.id, params[:basket][:size]]
    basket.each do |product| 
      if product[:product_id] == prod.id && product[:size] == params[:basket][:size] 
        product[:quantity] = product[:quantity] + params[:basket][:quantity].to_i
        flash.now[:success] = "Added to basket"
      end
    end 
  else     
    basket.add({product_id: prod.id, quantity: params[:basket][:quantity].to_i, size: params[:basket][:size]})
    flash.now[:success] = "Added to basket"
  end
  respond_to do |format|
    format.js
  end    
end


def destroy
  prod = Product.find(params[:product_id])
  @prod_name = prod.name
  if basket.to_a.collect{|item| [item[:product_id], item[:size]]}.include? [prod.id, params[:basket][:size]]
    basket.each do |product|
      if product[:product_id] == prod.id && product[:size] == params[:basket][:size]
        basket.delete(product)
        flash.now[:remove] = "Item removed from basket"
      end
    end 
  end       

  respond_to do |format|
    format.js
  end    
end

basket.to_a.collect{|item| [item[:product_id], item[:size]]}在日志中打印以下内容: 2

basket.to_a.collect{|item| [item[:product_id], item[:size]]}.include? [prod.id, params[:basket][:size]]返回错误

非常感谢

0 个答案:

没有答案