Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Active record. Model.Find.last

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?

like image 252
junkone Avatar asked Mar 20 '12 01:03

junkone


People also ask

Is ActiveRecord an ORM?

ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code.

What are ActiveRecord models?

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.

What is ActiveRecord relation?

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.

What is ActiveRecord Query?

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.


1 Answers

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.

like image 171
mu is too short Avatar answered Oct 11 '22 07:10

mu is too short