Find the Latest Entry in Rails 3

I was wondering if there is a way to find the newest record in a table in rails3?

thank

Elliot

+45
ruby ruby-on-rails ruby-on-rails-3
Feb 02 2018-11-11T00:
source share
5 answers

For the Post model, you can do @post = Post.order("created_at").last

(The reason I didn’t just do @post = Post.last is because it is always sorted by your primary key (usually id ) by default. In most cases, this is normal, but I'm sure there is a script where it can cause problems (for example, setting user identifiers in records, database changes that affect the primary key sequence / autostart, etc.) Sorting by the created_at label ensures that you really get the most recent record).

+95
Feb 02 2018-11-11T00:
source share

While dmarkow's answer is technically correct, you need to create an index on created_at or subject an ever slower query as your database grows.

If you know that your id column is the primary key of auto increment (which is probably the case), just use it because it is an index by definition.

In addition, if AREL is not optimized to select only one entry in find (: last), you run the risk of causing it to select ALL records and then return only the last to you using the "last ()" method. More effectively limiting the results to one:

 MyModel.last(:order => "id asc", :limit => 1) 

or

 MyModel.first(:order => "id desc", :limit => 1) 
+16
Feb 02 2018-11-11T00:
source share

Yes, you can use the .last method

So, if your model is called Post, then:

 >> Post.last => #<Post ...> 
+3
Feb 02 2018-11-11T00:
source share

Try for a model named ModelName :

 record = ModelName.last 
+2
Feb 02 2018-11-11T00:
source share

you may encounter ambiguity problems using created_at in a table with high enough traffic.

eg. try:

 INSERT INTO table (created_at) VALUES ( NOW() ); INSERT INTO table (created_at) VALUES ( NOW() ); 

.. has the potential to have the same created_at , which has only 1 second of resolution. sorting will return them in a specific order.

you might be better off saving the value of the microgrids and sorting it.

+2
Sep 21
source share



All Articles