如何在另一个模型中计算一个模型的数组变量?

How can I calculate Array variable of a Model in another Model?

我有一个简单的 Rails 应用程序。我正在尝试计算服务中 Instruments 的每个使用时间 Model.How 我可以在服务模型中计算它吗?

 class Service < ApplicationRecord
   has_many :instruments

   def total_usage
    # I want to sum the usage arrays which is from the Instrument model.
    # Here
  end
 end

 class Instrument < ApplicationRecord
   belongs_to :service, dependent: :destroy

   def usage
     outtime = self.out_time
     intime = self.in_time
     usage = ((outtime - intime)/60.0).round.abs
  end
end
def total_usage
  # or instruments.sum(&:usage) for short
  instruments.sum { |instrument| instrument.usage }
end

顺便说一句,dependent: :destroy应该放在has_many

之后
  has_many :instruments, dependent: :destroy

最好在数据库中进行简单的聚合和计算,这样您就可以使用它们来对记录进行排序:

# Postgres
Service.group(:id)
       .select(
         'services.*',
         'SUM(instruments.time_diff) AS usage'
       ).joins(
         'LATERAL (
            SELECT instruments.out_time - instruments.in_time AS time_diff
            FROM instruments
            WHERE instruments.service_id = services.id
         ) instruments'
       )

# MySql
Service.group(:id)
       .select(
         'services.*',
         'SUM(
           SELECT DATEDIFF(instruments.out_time, instruments.in_time) 
           FROM instruments
           WHERE instruments.service_id = services.id
         ) AS usage'
       )

如果您只需要聚合而不是整个记录,这也可以避免加载和实例化所有相关记录。