【问题标题】:nil can't be coerced into BigDecimalnil 不能被强制转换为 BigDecimal
【发布时间】:2012-02-21 08:14:24
【问题描述】:

大家好,我在 Rails 3 ruby​​ 1.9 环境下玩 RoR 我被困在了

nil 不能被强制转换为 BigDecimal

错误

我需要获取购物车内产品的总成本 我知道问题出在哪里(我想),但我几乎做了所有的事情

cart/show.html.rb

<div class="cart_title" >Your Cart</div>
    <table>
        <% for item in @cart.line_items %>
    <tr>
        <td><%= item.quantity %>&times;</td>
        <td><%= item.product.title %></td>
    <td class="item_price" ><%= number_to_currency(item.total_price) %></td>
    </tr>
    <% end %>
        <tr class="total_line" >
        <td colspan="2" >Total</td>
        <td class="total_cell" ><%= number_to_currency(@cart.total_price) %></td>
    </tr>
    </table>
        <%= button_to 'Empty cart', @cart, :method => :delete,
        :confirm => 'Are you sure?' %>

模型/line_item.rb

  def total_price
    line_items.to_a.sum { |item| item.total_price }
  end

模型/cart.rb

 def total_price
    product.price  * quantity
  end

我的第二个选择是

def total_price
     if product.price 
       product.price * quantity
     else
       product.price = "0.0".to_d
     end
   end

但这仍然行不通

感谢我们拥有更多的力量!

【问题讨论】:

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


    【解决方案1】:

    问题出在您的cart.rb 模型中:

    def total_price
      product.price  * quantity
    end
    

    您的购物车中没有一件商品;您的购物车中有 许多 产品。您需要将购物车中所有行项目的所有价格相加。 (您希望使用订单项,而不是直接使用产品,以防客户承诺以旧价格购买产品后产品价格发生变化。)

    您将如何解决这个问题取决于您的模型的详细信息,但您会寻找这样的东西:

    def total_price
        line_items.to_a.each(&:total_price).sum
    end
    

    这将对您的 line_items 集合中的每个项目运行 total_price 方法,构建所有项目的列表,然后 sum 列表。

    【讨论】:

    • 我该怎么做?你能给我举个例子吗,我是 RoR 的新手,谢谢:)
    猜你喜欢
    • 2012-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多