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?
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 byidis just a convenient accident.You should do one of these:
That will give you the execution for
tradethat has the highestid. If you really want the most recently created one then you shouldorder(:created_at)instead:The
idandcreated_atcolumns 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).lastandorder('x desc').firstare exactly the same and even resolve to exactly the same SQL so use whichever one makes the most sense to you.