活动记录。型号查找 [英] Active record. Model.Find.last

查看:98
本文介绍了活动记录。型号查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在交易执行之间具有ActiveRecord关系。我可以得到

I have an ActiveRecord relationship between Trade and Execution. I can get

Trade.executions  #returns all exeuctions realated to the Trade

如果我愿意

Trade.executions.last

似乎似乎根据ID返回最后一次执行记录。

It seems seems to return the last execution record based on ID.

这是基于ID检索与交易相关的最后执行记录的正确方法吗?

Is this the correct way to retrieve the last execution record related to Trade based on ID?

推荐答案

否,这不能保证为您提供最高 id 的执行。如果未指定明确的顺序,则记录可以任何顺序从数据库中取出。他们看起来像是按 id 进行排序的事实只是一个方便的事故。

No, that's not guaranteed to give you the Execution with the highest id. If you don't specify an explicit ordering then the records can come out of the database in any order. The fact that they look like they're sorted by id is just a convenient accident.

您应该做一个其中的

highest_id_execution = trade.executions.order(:id).last
highest_id_execution = trade.executions.order('id desc').first

这将为您执行贸易具有最高的 id 。如果您确实想要最近创建的一个,则应该 order(:created_at)代替:

That will give you the execution for trade that has the highest id. If you really want the most recently created one then you should order(:created_at) instead:

most_recent_execution = trade.executions.order(:created_at).last
most_recent_execution = trade.executions.order('created_at desc').first

id created_at 列几乎总是以相同的顺序出现,但是您应该说出自己的意思,以便使维护代码的人员更清楚地了解事情。

The id and created_at columns will almost always come in the same order but you should say what you mean to make things clearer to the people that maintain your code.

在两种情况下, order(:x).last order('x desc')。first 完全相同,甚至可以解析为完全相同的SQL因此,请使用对您最有意义的一种。

In both cases, the order(:x).last and order('x desc').first are exactly the same and even resolve to exactly the same SQL so use whichever one makes the most sense to you.

这篇关于活动记录。型号查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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