ruby-on-railsrubyactiverecord

How to use several aggregate functions at once in Rails/ActiveRecord?


I want to do several aggregate functions at once, eg to get the max and min id's grouped by status:

Model.maximum(:id).minimum(:id).group(:status)

This doesnt work (at least with Rails 3.1.1) - you get an error on the minimum call, saying its not defined on Fixnum.

NoMethodError: undefined method `minimum' for 22377:Fixnum

I could do raw sql for it - but just wondering if there is a higher level/Rails option...

Thanks, Chris


Solution

  • I believe @topek is right that you can't chain the calculation functions like this. I think you'll have to use SQL in a select predicate, e.g.:

    Model.select('MAX(id) AS `maximum`, MIN(id) AS `minimum`').group(:status)
    

    I just tested this in a project of my own and it appears to work as expected.