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.