0

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?

4

1 回答 1

0

I've found the answer I was looking for. Turns out it could be done chaining joins, maximum and where:

Property.where(:collection_name => 'some_name').joins(:audio).maximum('starts_at + length')

(0.2ms) SELECT MAX(starts_at + length) AS max_id FROM "properties" INNER JOIN "audios" ON "audios"."id" = "properties"."audio_id" WHERE "properties"."collection_name" = 'some_name'

=> 6038

于 2013-06-07T04:55:34.053 回答