Adam22
(Adam)
August 28, 2011, 5:52pm
1
I have a model, blog_posts which has a field "published_at". I'd like
to select the latest two blogs from that model to display on my
homepage. Not sure how to structure that though.
At the moment I have a work around that takes a slice of the data but
it keeps failing when I have nothing in the table, rather than fix
this I feel there is probably a better way to retrieve the data.
I need to select the blogs in separate calls, for example
@blog_post.latestpost , @blog_post.secondlatestpost
Thanks, Adam
11155
(-- --)
August 28, 2011, 6:25pm
2
Create a named_scope (scope in Rails 3) like this:
scope :secondlatestpost, :limit => 2, :order => :published_at
Then declare it as follows:
BlogPost.secondlatestpost
BTW IMHO the method name 'secondlatestpost' is a little long. I should
take a name like BlogPost.latest
hassan
(Hassan Schroeder)
August 28, 2011, 7:04pm
3
Create a named_scope (scope in Rails 3) like this:
scope :secondlatestpost, :limit => 2, :order => :published_at
Or for some flexibility:
scope :latest, lambda {|number| { :order => :updated_at, :limit => number } }
BlogPost.latest
then you can ask for e.g. BlogPost.latest 2 or BlogPost.latest 5
(and with no number specified get them all in update order).
FWIW,
Create a named_scope (scope in Rails 3) like this:
scope :secondlatestpost, :limit => 2, :order => :published_at
Or for some flexibility:
scope :latest, lambda {|number| { :order => :updated_at, :limit => number } }
just a note .. request was for LAST two records… with this order query will return first two records, assume use
:order => 'published_at desc'
hassan
(Hassan Schroeder)
August 29, 2011, 4:03pm
5
D'oh -- good point, thanks for catching that.
And of course my example should have used 'published_at' rather
than 'updated_at'; fingers on autopilot!