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?
ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code.
1 What is Active Record? Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.
The Relation Class. Having queries return an ActiveRecord::Relation object allows us to chain queries together and this Relation class is at the heart of the new query syntax. Let's take a look at this class by searching through the ActiveRecord source code for a file called relation.
Active Record insulates you from the need to use SQL in most cases. Active Record will perform queries on the database for you and is compatible with most database systems, including MySQL, MariaDB, PostgreSQL, and SQLite.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With