Best form in pulling the last two records from a dataset in active record

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

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

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'

:slight_smile:

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!