【问题标题】:Can't understand how to sum items price checkout in RoR无法理解如何在 RoR 中总结项目价格结帐
【发布时间】:2015-08-10 04:42:03
【问题描述】:

如何根据价格乘以数量获得商品的 grad_total?

    def grand_total
      grand_total = 0
      line_items.each do |item|
        grand_total += item.quantity * item.phone.price
      end   
      grand_total
    end

【问题讨论】:

  • 这个问题没有问题,也没有按照规则格式化。
  • 你想问什么?请仔细阅读有关如何发布问题的指南。

标签: ruby-on-rails


【解决方案1】:

如果你有一个包含多个记录的活动记录对象,你会想尝试这样的事情。

class << self
   def grand_total
     self.phone.price * self.quantity
   end
end

【讨论】:

    【解决方案2】:

    您可能想在名为 cart 的数据库中创建一个类。 此类将包含有关产品的信息。

    create_table "cart", force: true do |t|
        t.integer  "product_id"
        t.integer  "quantity", default(1), not null
        t.integer  "user_id"
        ...
        t.datetime "created_at"
        t.datetime "updated_at"
      end
    

    现在我们在这个类上有一个购物车,我们现在可以做这样的事情:

    #cart.rb
    class Cart < ActiveRecord::Base
      belongs_to :product
      belongs_to :user
      ...
      def grand_total
        product.price.to_f * quantity.to_i
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-10
      • 2013-04-07
      • 2020-06-26
      • 1970-01-01
      • 2021-01-25
      • 1970-01-01
      • 2015-03-17
      相关资源
      最近更新 更多