[英]rails - activerecord SELECT TOP 1 field_name * FROM table_name
I have a sql like this:我有一个这样的sql:
SELECT TOP 1 field_name * FROM table_name
and I want to covert it into activerecord in rails.我想将其转换为 rails 中的 activerecord。
That code doesn't do the job?那个代码不起作用?
YourModel.select(:field_name).first
or要么
YourModel.select(:field_name).order('id desc').first
只需使用limit(1)
或first
:
Model.select(:field_name).limit(1)
Since Rails 6, you can use the following:从 Rails 6 开始,您可以使用以下内容:
YourModel.order(id: :desc).pick(:field_name)
pick is even more efficient than pick甚至比
YourModel.select(:field_name).order('id desc').first
since, it will only load the actual value, not the entire record object.因为,它只会加载实际值,而不是整个记录对象。
For more details, please, follow this link to docs .有关更多详细信息,请点击此链接至 docs 。
Also, there is a reference to the corresponding PR .此外,还有对相应 PR的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.