积极的记录。 Model.Find.last

我在TradeExecution之间有一个ActiveRecord关系。 我可以得到

 Trade.executions #returns all exeuctions realated to the Trade 

如果我做

 Trade.executions.last 

似乎似乎返回基于ID的最后一个执行记录。

这是根据ID检索与Trade相关的最后一条执行记录的正确方法吗?

不,这不能保证给你最高id的执行。 如果未指定显式排序,则记录可以按任何顺序从数据库中输出。 事实上,他们看起来像是按照id排序,这只是一个方便的事故。

你应该做其中一个:

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

这将为您提供具有最高id trade的执行。 如果你真的想要最近创建的那个,那么你应该order(:created_at)

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

idcreated_at列几乎总是以相同的顺序排列,但你应该说出你的意思是让维护代码的人更清楚。

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

#last将根据主键返回最后一条记录。 如果您的主键不是id ,那么您需要更明确。

这是在文档和代码中

正如@muistooshort所提到的那样明确:)