How to categorise a blog posts data by month in Ruby On Rails

Suppose we created a ‘BlogPost’ Model in Rails and we 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
Advertisements

Author: Abhilash

Hi, this is Abhilash - Senior Programmer Analyst at CoMakeIT, specialised on web programming. Mainly working on Ruby On Rails platform since 2010.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s