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.
On Feb 6, 2012, at 11:54 AM, Christopher J. wrote:
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?
–
Scott R.
[email protected]
http://www.elevated-dev.com/
(303) 722-0567 voice
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
2012/2/6 Christopher J. [email protected]
On Feb 6, 2012, at 12:37 PM, Christopher J. wrote:
Game.find(:all, :limit => 5, :order=> ‘created_at’)
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)
–
Scott R.
[email protected]
http://www.elevated-dev.com/
(303) 722-0567 voice
On Feb 6, 2012, at 1:37 PM, Christopher J. wrote:
<% Game.all().order(‘created_at desc’).limit(5) %>
or does it go in the model?
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.
–
Scott R.
[email protected]
http://www.elevated-dev.com/
(303) 722-0567 voice
Cheers for all the help, it worked a treat.
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