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

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.


You could also do:

BlogPost.order(:published_at).last # for the last post
BlogPost.order(:published_at).offset(1).last # for the second to last post

As of Rails 5 you can use BlogPost.second_to_last.

http://api.rubyonrails.org/v5.0/classes/ActiveRecord/FinderMethods.html#method-i-second_to_last