150

Currently I can make the straight-up SQL query on my DB:

SELECT MAX(bar) FROM table_name

And it returns with the max value in that table. When I make what I consider to be an equivalent call in Rails, however, it does not work. I am calling:

Bar.all(:select => "Max(bar)")

This simply returns with:

[#<Bar >]

In the column I'm calling on is a series of identifying numbers, I'm looking for the largest one. Is there some other way of accessing this in Rails?

2 Answers 2

328

Assuming your model name is Bar and it has a column named bar, this should work:

Bar.maximum(:bar)

See the excellent Rails Guides section on Calculations :: Maximum for more info.

1
  • Ah ha! Right you are, that did it. I'll check your answer off as the one soon as SO will let me. Thanks!
    – keybored
    Feb 11, 2011 at 21:09
10

one more way

Bar.select("Max(bar) as max_bar").first.max_bar
5
  • 6
    Why would you want to do this? More verbose, and executes the exact same query as Bar.maximum(:bar) so I see no reason to "recommend" this answer at all ...
    – nathanvda
    Oct 27, 2014 at 15:42
  • 24
    for example, if you want both min and max: Bar.select("MAX(bar) max_bar, MIN(bar) min_bat").first.attributes May 19, 2015 at 9:52
  • 2
    The person asking the question only wanted max. Sep 15, 2015 at 20:18
  • 4
    He did provide an correct answer for the question. Probably it's not the best answer, but he did nothing wrong with it.
    – david0116
    Nov 19, 2019 at 10:21
  • 3
    I think it has value as it shows an example of using a function inside of .select which is knowledge that could be helpful in executing a similar query where you want to select multiple things.
    – Gino
    May 16, 2022 at 10:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.