简体   繁体   English

Ruby on Rails:从数据库列中获取最大值

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

Currently I can make the straight-up SQL query on my DB:目前我可以在我的数据库上进行直接 SQL 查询:

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.但是,当我在 Rails 中进行我认为等效的调用时,它不起作用。 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?在 Rails 中还有其他方法可以访问它吗?

Assuming your model name is Bar and it has a column named bar , this should work:假设您的模型名称是Bar并且它有一个名为bar的列,这应该有效:

Bar.maximum(:bar)

See the excellent Rails Guides section on Calculations :: Maximum for more info.有关更多信息,请参阅关于计算 :: 最大值的优秀 Rails 指南部分。

另一种方式

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM