【问题标题】:Rails undefined method for ActiveRecord::Relation error calculating cart items用于 ActiveRecord::Relation 错误计算购物车项目的 Rails 未定义方法
【发布时间】:2012-11-02 10:41:29
【问题描述】:

我正在尝试计算购物车中包含的所有商品的总价。但是我收到了undefined method total_cart_price for ActiveRecord::Relation:xxx

购物车模型 (shop_cart.rb)

has_many :shop_cart_items, :dependent => :destroy


  def total_cart_price
    shop_cart_items.to_a.sum { |item| item.total_price }
  end

购物车商品模型 (shop_cart_item.rb)

attr_accessible :quantity, :shop_cart_id, :shop_product_id

  belongs_to :shop_product
  belongs_to :shop_cart


  def total_price
    shop_product.sell * quantity
  end

购物篮视图 (shop/basket.html.erb)

<tbody>
    <% @cart_items.each do |item| %>
        <tr>
        <td><%= item.shop_product.name %></td>
        <td><%= number_to_currency(item.shop_product.sell) %></td>
        <td><%= item.quantity %></td>
        <td><%= number_to_currency(item.total_price) %></td>
        </tr>
    <% end %>
    <tr>
    <td></td>
    <td></td>
    <td>Subtotal:</td>
    <td><%= number_to_currency(@cart_items.total_cart_price) %></td>
    </tr>
</tbody>

单件商品的总价很好;错误是试图计算所有项目的总和。

我没有 shop_cart 控制器或视图,因为我从 shop#basket 视图调用方法 - 不确定这是否是导致问题的原因?

非常感谢任何帮助。

【问题讨论】:

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


    【解决方案1】:

    试试这个, @cart_items.shop_cart.total_cart_price 这是一个购物车方法。

    【讨论】:

    • 嗨,这给了我 ActiveRecord::Relation 的未定义方法 `shop_cart'
    • 哦,你有 @shop_cart 变量 ins 控制器你可以使用这个或 @cart_items.first.shop_cart.total_cart_price
    • 太好了,谢谢。使用了@cart_items.first,虽然我只能得到购物车中第一项的总和,但它已经奏效了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 2021-09-24
    • 2015-08-09
    • 2013-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多