Suppose we have created a ‘BlogPost’ Model in Rails and it have the following fields in a blog post:
title – title of the blog post
posted_on – date posted
permalink – a permanent link of each blog post (act as a primary key)
publish – a boolean field which decides the post need to show or not
Lets write a method in ‘BlogPost’ Model to get a recent list of posts.
Pass a ‘months_old’ parameter to determine how much months old posts we wanted to list.
Just select the required columns to show the details of the post (by ‘:select => ‘). And Group each post by posted month.
def self.get_recent_months_post(months_old)
@blog_posts = where("publish = ? AND posted_on > ?", true, Date.today - months_old.months).all(:select => "title, posted_on, permalink", :order => "posted_on DESC")
(@blog_posts.group_by { |t| t.posted_on.beginning_of_month }).sort.reverse
end
We successfully written the method above. Now lets write a method to get the archives (old posts).
def self.get_archives(old)
@blog_posts = where("publish = ? AND posted_on "title, posted_on, permalink", :order => "posted_on DESC")
(@blog_posts.group_by { |t| t.posted_on.beginning_of_month }).sort.reverse
end