在 Rails 3 中查找最新记录 [英] Find the newest record in Rails 3

查看:35
本文介绍了在 Rails 3 中查找最新记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有办法在 rails3 的表中找到最新的记录?

I was wondering if there is a way to find the newest record in a table in rails3?

推荐答案

给定一个 Post 模型,你可以做 @post = Post.order("created_at").last

Given a Post model, you could do @post = Post.order("created_at").last

(我不只是做一个 @post = Post.last 的原因是因为它总是默认按你的主键(通常是 id)排序).有时这很好,但我确信在某些情况下这可能会导致问题(例如,在记录上设置自定义 ID、影响主键排序/自动编号的数据库更改等).按 created_at 排序 时间戳确保您确实获得了最新的记录).

(The reason I didn't just do a @post = Post.last is because that always defaults to sort by your primary key (usually id). Most of the time this is fine, but I'm sure there's a scenario where that could cause problems (e.g. setting custom IDs on records, database changes which affect the primary key sequencing/autonumbering, etc.). Sorting by the created_at timestamp ensures you are really getting the most recent record).

这篇关于在 Rails 3 中查找最新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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