【问题标题】:undefined method `*' for nil:NilClassnil:NilClass 的未定义方法“*”
【发布时间】:2012-12-27 01:28:24
【问题描述】:

我在使用 acts-as-shopping-cart gem 时遇到此错误:

undefined method `*' for nil:NilClass  Extracted source (around line #5):

2:
3: <%= render :partial => 'shopping_cart_item', :collection => @shopping_cart.shopping_cart_items %>
4:
5:  SubTotal:<%= number_to_currency @shopping_cart.subtotal %>
6:  Taxes:<%= number_to_currency @shopping_cart.taxes %>
7:  Total:<%= number_to_currency @shopping_cart.total %>

这些字段似乎是在 gem 源中定义的。

show.html.erb

<h1>Shopping Cart</h1>

<%= render :partial => 'shopping_cart_item', :collection => @shopping_cart.shopping_cart_items %>

<div><b>SubTotal:</b><%= number_to_currency @shopping_cart.subtotal %></div>
<div><b>Taxes:</b><%= number_to_currency @shopping_cart.taxes %></div>
<div><b>Total:</b><%= number_to_currency @shopping_cart.total %></div>

shopping_cart.rb

class ShoppingCart < ActiveRecord::Base
  acts_as_shopping_cart

  def tax_pct
    8.25
  end

  def taxes
    (subtotal - 10) * tax_pct
  end

end

应用程序跟踪

app/views/shopping_carts/show.html.erb:5:in `_app_views_shopping_carts_show_html_erb__2338506009803118188_70153042369260'

shopping_carts.controller

class ShoppingCartsController < ApplicationController
  before_filter :extract_shopping_cart

  def create
    @product = Product.find(params[:product_id])
    @shopping_cart.add(@product, @product.price)
    redirect_to shopping_cart_path
  end

  def show

  end

  private
  def extract_shopping_cart
    shopping_cart_id = session[:shopping_cart_id]
    @shopping_cart = session[:shopping_cart_id] ? ShoppingCart.find(shopping_cart_id) : ShoppingCart.create
    session[:shopping_cart_id] = @shopping_cart.id
  end
end

我的仓库

https://github.com/atbyrd/Bootstrapped_Devise

【问题讨论】:

  • 该异常是否有堆栈跟踪?哪个* 导致了问题?
  • @muistooshort 发布的代码中只有一个..这[很可能]不是罪魁祸首:(
  • @pst:是的,我希望首先抱怨NilClass 不理解-,所以有趣的部分根本不在问题中。
  • @muistooshort 我用完整的错误更新帖子
  • @shopping_cart.subtotal 会以nil 的形式出现吗?也许number_to_currency 试图在内部进行乘法运算。

标签: ruby-on-rails ruby acts-as-shopping-cart


【解决方案1】:

仅当您将未定价商品添加到购物车时才会出现此问题。

所以你需要确保所有产品都有价格,可能使用验证,可能使用 before_save 函数,但确保所有产品都有价格,这个问题就会消失。

ps在测试之前不要忘记从您的数据库中清除任何未定价的产品

【讨论】:

  • 这看起来不错。该错误表明问题出在第 5 行,其中唯一被评估的是@shopping_cart.subtotal。如果您查看小计的实现,您会看到它遍历购物车中的项目并执行item.price * item.quantity。这表明某些item.pricenil
猜你喜欢
  • 2011-07-27
  • 2013-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多