Active record. Model.Find.last

China☆狼群 提交于 2019-12-12 12:02:11

问题


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

Trade.executions  #returns all exeuctions realated to the Trade

If I do

Trade.executions.last

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

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


回答1:


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.

You should do one of these:

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

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

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.

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.




回答2:


#last will return the last record based on primary key. If your primary key is not id, then you will need to be more explicit.

This is both in the documentation and the code

As @muistooshort mentioned, it doesn't hurt to be explicit :)



来源:https://stackoverflow.com/questions/9780169/active-record-model-find-last

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!