Ruby on Rails:从数据库列中获取最大值 [英] Ruby on Rails: getting the max value from a DB column

查看:34
本文介绍了Ruby on Rails:从数据库列中获取最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我可以在我的数据库上进行直接的 SQL 查询:

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

SELECT MAX(bar) FROM table_name

它返回该表中的最大值.然而,当我在 Rails 中进行我认为是等效的调用时,它不起作用.我打电话:

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)")

这只是返回:

[#<Bar >]

在我要调用的列中是一系列识别数字,我正在寻找最大的一个.在 Rails 中还有其他访问方式吗?

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?

推荐答案

假设您的模型名称是 Bar 并且它有一列名为 bar,这应该可以:

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

Bar.maximum("bar")

有关详细信息,请参阅优秀的Rails 指南部分关于计算.

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

这篇关于Ruby on Rails:从数据库列中获取最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆