【问题标题】:Rails order by has_many :through attribute sum通过has_many进行Rails排序:通过属性总和
【发布时间】:2018-04-10 16:04:24
【问题描述】:

我需要按遥测值的总和对分类进行排序。

这些是我的模型:

class Assortment < ApplicationRecord
  has_many :sensors
  has_many :telemetries, through: :sensors
end

class Sensor < ApplicationRecord
  belongs_to :assortment, optional: true
  has_many :telemetries, dependent: :destroy
end

class Telemetry < ApplicationRecord
  belongs_to :sensor
end

这就是我可以通过遥测值的总和来订购传感器的方式:

Sensor.joins(:telemetries).group("sensors.id", "telemetries.sensor_id").order("sum(telemetries.value) desc")

但是我怎样才能为分类做同样的事情呢? (我用的是 PostgreSQL)

【问题讨论】:

    标签: sql ruby-on-rails postgresql active-record-query sql-order-by


    【解决方案1】:

    好的,结果很简单:

    Assortment.joins(:telemetries).group("assortments.id", "telemetries.sensor_id").order("sum(telemetries.value) desc")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-19
      • 2011-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多