Reputation: 1465
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?
Upvotes: 6
Views: 9534
Reputation: 2800
#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 :)
Upvotes: 1
Reputation: 434665
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.
Upvotes: 15