I have 2 models: a station
and sensor_value
that are related by the station id.
class Station < ApplicationRecord
has_many :sensor_values, primary_key: :station_id, foreign_key: :station_id, dependent: :destroy
validates :station_id, presence: true, uniqueness: true
end
class SensorValue < ApplicationRecord
belongs_to :station, primary_key: :station_id, foreign_key: :station_id
validates :value, :type, :station_id, presence: true
end
One station
can have several sensor values
, each of sensor values
saves different types of values (temperature, humidity, light).
I need to get the average for all the latest indicators from each station.My current solution to get the average temperature across all stations:
def last_sensors_values
temperature = []
Station.all.each do |st|
next if st.sensor_values.empty?
temperature_val = st.sensor_values.where(type: 'temperature').last.value
temperature.push(temperature_val) unless temperature_val.zero?
end
{
temperature: temperature.sum / temperature.size
}
end
But I think it can be done with SQL, any ideas on how to improve this code?
Thanks for any help)
Updated: Rails 5.2.5 Database PostgreSQL >= 10