【问题标题】:ActiveRecord sum活动记录总和
【发布时间】:2015-11-26 03:28:12
【问题描述】:

我有一个模型,其中包含待售物品。该模型正在镜像 API,因此我无法更改其结构。

在这个模型中,我有 pricesold_quantity 字段。

用循环遍历查询似乎不正确。

current_user.items.each do |item|
  total += item.price * item.sold_quantity
end

有没有办法只使用 ActiveRecord 来获得相同的总数?类似于.sum(:price),但乘以sold_quantity

【问题讨论】:

  • 刚刚找到比丑陋循环更好的方法,但它仍然会遍历结果。在这个主题stackoverflow.com/questions/25274845/…我找到了通过模型实例方法求和的方法@items.to_a.sum(&:sold_value)

标签: ruby-on-rails ruby activerecord


【解决方案1】:

你可能想要这个:

current_user.items
  .select('items.*, items.price * items.sold AS total')
  .all

或者,如果您只想要总数而不需要其他任何东西:

current_user.items.pluck('items.price * items.sold')

【讨论】:

  • 这确实有效,但它返回一个包含所有乘法结果的数组。刚刚添加.inject(:+)
  • current_user.items.pluck('items.price * items.sold').inject(:+)
  • 我认为current_user.items.sum('items.price * items.sold') 会做同样的事情,但在数据库中。
【解决方案2】:

你可以这样做:

current_user.items.sum { |item| item.price * item.sold_quantity }

希望对你有所帮助。

更多信息sumAR

【讨论】:

  • 你没有在这里使用 ActiveRecord。您正在使用(并链接到)的方法是来自 ActiveSupport 的 Enumerable#sum。
【解决方案3】:

解决此问题的一种方法是将这个逻辑移到 Item 类中:

class Item < ActiveRecord::Base
  ...

  def total
    self.price * self.sold_quantity
  end

  def self.sold_value
    all.map{|a| a.total}.sum
  end
end

这里的每个 item 实例都在计算它自己的总数,并且类方法允许您获取任何项目集合的销售价值。

@user.items.sold_value

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    • 2013-12-30
    • 1970-01-01
    • 1970-01-01
    • 2011-02-28
    • 1970-01-01
    相关资源
    最近更新 更多