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

On Aug 28, 2011, at 21:04 , Hassan S. wrote:

On Sun, Aug 28, 2011 at 11:25 AM, Jeroen van Ingen [email protected] wrote:

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:


You received this message because you are subscribed to the Google G. “Ruby
on Rails: Talk” group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en.

Tomas Meinlschmidt, MS {MCT, MCP+I, MCSE, AER}, NetApp Filer/NetCache

www.meinlschmidt.com www.maxwellrender.cz www.lightgems.cz

On Sun, Aug 28, 2011 at 12:21 PM, Tom M.
[email protected] wrote:

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’

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!


Hassan S. ------------------------ [email protected]

twitter: @hassan

On Sun, Aug 28, 2011 at 11:25 AM, Jeroen van Ingen
[email protected] wrote:

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,

Hassan S. ------------------------ [email protected]

twitter: @hassan