Active record. Model.Find.last

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 to return the last execution record based on ID.

Is this the right way to get the latest execution record related to Trade based on ID?

+4
source share
2 answers

No, this does not guarantee that you will execute Execution with the highest id . If you do not specify explicit ordering, records can exit the database in any order. The fact that they look like they are sorted by id is just a convenient crash.

You must do one of the following:

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

This will give you the execution for trade with the highest id . If you really want to create the latter, 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 almost always be in the same order, but you have to say what you want to make more understandable to the people who support your code.

In both cases, order(:x).last and order('x desc').first are exactly the same and even allowed exactly the same SQL, so use what suits you best.

+11
source

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

This is both in the documentation and in the code

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

+1
source

Source: https://habr.com/ru/post/1402345/


All Articles