I'm struggling to build a query in Rails which returns me the max value of adding two columns of two different tables. I have two models, lets name them Audio
and Property
, where Property
has the columns "id, audio_id, starts_at, collection_name"
, and Audio has "id and length"
. What I'd like to do is to build the following SQL query in Rails:
SELECT MAX(property.starts_at + audio.length) FROM audio
INNER JOIN property WHERE property.audio_id = audio.id
AND property.collection_name = 'some_name';
The associations are simply belongs_to :audio
for Property and has_many :properties
for Audio. I could build this retrieving every Property where collection_name is 'some_name', iterating through each of them, saving the max to a variable and returning the max value:
def full_length
full_lengths = []
Property.where(:collection_name => 'some_name').each do |p|
full_lengths << p.audio.length + p.starts_at
end
full_lengths.max
end
But that don't look so good performancewise nor seems to be the Ruby/Rails way to do it. Is there any combination of ActiveRecord methods which would allow me to do this?