Search code examples
sqlruby-on-railspostgresqlactive-record-querysql-order-by

Rails order by has_many :through attribute sum


I need to order Assortments by a sum of Telemetries' values.

These are my models:

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

This is how I can order Sensors, by the sum of telemetries' values:

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

But how can I do the same for Assortments? (I use PostgreSQL)


Solution

  • ok, it turned out to be very easy:

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