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.
source share