Ruby on Rails: getting the max value from a DB column

SqlRuby on-Rails

Sql Problem Overview


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?

Sql Solutions


Solution 1 - Sql

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 for more info.

Solution 2 - Sql

one more way

Bar.select("Max(bar) as max_bar").first.max_bar

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkeyboredView Question on Stackoverflow
Solution 1 - SqlDylan MarkowView Answer on Stackoverflow
Solution 2 - SqlManish KaseraView Answer on Stackoverflow