Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pick the last and the second to last entries in a blog model?

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

like image 687
Adam Avatar asked Aug 28 '11 17:08

Adam


1 Answers

Is this what you're looking for? :

class BlogPost < Activerecord::Base
  def self.latestpost
    order("published_at DESC").limit(1).first
  end

  def self.secondlatestpost
    order("published_at DESC").offset(1).limit(1).first
  end
end

Use it like this :

BlogPost.secondlatestpost

or

BlogPost.latestpost

Hope this helps.

like image 129
Benoit Garret Avatar answered Sep 30 '22 09:09

Benoit Garret