Display by Timestamps?

Hi All,

I am wondering if anyone has any information on displaying records based
on their timestamp.

I want to on the front page of the website display the 3 most recently
uploaded games. I imagine I would do this by extracting the three games
with the most recent timestamp?

Any information/links/tutorials/articles/input will be appreciated.

Thanks

Maybe you don't know about the limit clause?

order by sometimestamp desc limit 3

And at least in Rails 3, limit is explicitly supported so you don't have to drop to SQL to do this.

Maybe you don't know about the limit clause?

I had never previously heard of it but just done some research.

Is this the sort of thing you mean?

Game.find(:all, :limit => 5, :order=> 'created_at')

?

Thanks

If you are constantly using this order clause i recommend you create a scope in your model.

scope :recent_games, order(“created_at desc”).limit(5)

then in your controller you call the scope like:

@var = Class.all.recent_games

Roughly, that's the first 5 created not the last, so you'd need to sort in descending order. These days I'm going new-school:

Game.all().order('created_at desc').limit(5)

Game.all().order('created_at desc').limit(5)

So would this go in my index.html as the following?

<% Game.all().order('created_at desc').limit(5) %>

or does it go in the model?

Thanks

It'll work in either place. (Of course regardless you need the .each() do |game| part in the template...)

But I'd put it in the controller as @recent_games =... Generally stuffing database access into the .html.erb makes things more complicated than they should be. And I would not consider "get the last 5 created..." of anything to be part of the model--unlike say routines to parse or format for standard display.

Cheers for all the help, it worked a treat. :slight_smile: