【问题标题】:How can I calculate Array variable of a Model in another Model?如何计算另一个模型中模型的数组变量?
【发布时间】:2022-01-15 16:01:53
【问题描述】:

我有一个简单的 Rails 应用程序。我正在尝试计算服务模型中 Instruments 的每次使用时间。如何在服务模型中计算它?

 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

【问题讨论】:

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


    【解决方案1】:

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

    # 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'
           )
    

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

    【讨论】:

      【解决方案2】:
      def total_usage
        # or instruments.sum(&:usage) for short
        instruments.sum { |instrument| instrument.usage }
      end
      

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

        has_many :instruments, dependent: :destroy
      

      【讨论】:

      • 依赖可以在关联的任一侧声明。
      • 你是对的。这是我第一次知道……;但是,我认为不建议对 has_many->belongs_to 关系这样做
      • 这完全取决于它的使用方式。
      • 谢谢。它有效!
      • @ShimolKhan 如果您认为此解决方案还可以,请将其设置为最佳答案:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-19
      • 2016-11-12
      • 2020-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多