Ruby-on-rails 在 Rails 3 中查找最新记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4870531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:17:04  来源:igfitidea点击:

Find the newest record in Rails 3

ruby-on-railsrubyruby-on-rails-3

提问by Elliot

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

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

Thanks

谢谢

Elliot

艾略特

回答by Dylan Markow

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

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

(The reason I didn't just do a @post = Post.lastis 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_attimestamp ensures you are really getting the most recent record).

(我不只是做 a 的原因@post = Post.last是因为它总是默认按你的主键排序(通常id是记录上的 ID、影响主键排序/自动编号的数据库更改等)。按created_at时间戳排序可确保您真正获得最新的记录)。

回答by jemminger

While dmarkow's answer is technically correct, you'll need to make an index on created_at or risk an increasingly slow query as your database grows.

虽然 dmarkow 的答案在技术上是正确的,但您需要在 created_at 上创建索引,否则随着数据库的增长,查询会越来越慢。

If you know that your "id" column is an auto-increment primary key (which it likely is), then just use it since it is an index by definition.

如果您知道您的“id”列是一个自动递增的主键(它很可能是),那么就使用它,因为它是定义的索引。

Also, unless AREL is optimized to select only one record in a find(:last), you run the risk of making it select ALL records, then return you just the last one by using the "last()" method. More efficient is to limit the results to one:

此外,除非 AREL 被优化为在 find(:last) 中只选择一条记录,否则你会冒着让它选择所有记录的风险,然后使用“last()”方法只返回最后一条记录。更有效的是将结果限制为一个:

MyModel.last(:order => "id asc", :limit => 1)

or

或者

MyModel.first(:order => "id desc", :limit => 1)

回答by RUN-CMD

you may run into ambiguity issues using created_aton a sufficiently high-traffic table.

created_at在足够高的流量表上使用时,您可能会遇到歧义问题。

eg. try:

例如。尝试:

INSERT INTO table (created_at) VALUES ( NOW() );
INSERT INTO table (created_at) VALUES ( NOW() );

..has the potential to have the same created_at, which only has 1 second of resolution. a sort would return them in no particular order.

..具有相同的潜力created_at,只有 1 秒的分辨率。排序不会以特定的顺序返回它们。

you may be better off storing a microtime value and sorting on that.

您最好存储一个微时间值并对其进行排序。

回答by Sam Ritchie

Try, for a model named ModelName:

尝试,对于名为 的模型ModelName

record = ModelName.last

回答by DanneManne

Yes, you can use the method .last

是的,您可以使用 .last 方法

So if your model is called Post then:

因此,如果您的模型名为 Post,则:

>> Post.last
=> #<Post ...>