nil无法在视图中强制进入Float

时间:2016-02-27 22:03:18

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

我有这个错误:

app/views/carts/show.html.erb:6 raised:

nil can't be coerced into Float

型号:

class CartItem
  attr_reader :product_id, :quantity

  def  initialize (product_id, quantity= 1)
    @product_id = product_id
    @quantity = quantity
  end

  def increment
    @quantity = @quantity + 1
  end

  def product
    Product.find product_id
  end

  def total_price
    product.price * quantity
  end
end

查看:

<% @cart.items.each do |item|%>
  <table class="table table-hover">
    <tr>
      <td><%= item.quantity %></td>
      <td><%= item.product.name %></td>
      <td><%= item.total_price %></td>
    </tr>
  </table>
<% end %>

控制器:

class CartsController < ApplicationController
  before_filter :initialize_cart

  def add
    @cart.add_item params[:id]
    session['cart'] = @cart.serialize
    product = Product.find params[:id]
    redirect_to :back, notice:  "Added #{product.name} to cart."
  end

  def show; end
end

1 个答案:

答案 0 :(得分:3)

而不是

def total_price
    product.price * quantity
end
你应该

def total_price
    product.price * @quantity
end

因为@quantity是一个实例变量。