Group and sort blog posts by date in Rails

Posted by Senthil on Stack Overflow See other posts from Stack Overflow or by Senthil
Published on 2010-04-28T02:48:47Z Indexed on 2010/04/28 2:53 UTC
Read the original article Hit count: 245

Filed under:

I've searched all over web and have not found the answer. I'm trying to have a very standard archive option for my blog based on date. A request to url blog.com/archive/2009 shows all posts in 2009, blog.com/archive/2009/11 shows all posts in November 2009 etc. I found two different of code but not very helpful to me.

def display_by_date
 year = params[:year]
 month = params[:month]
 day = params[:day]
 day = '0'+day if day && day.size == 1
 @day = day
 if (year && month && day)
   render(:template => "blog/#{year}/#{month}/#{date}")
 elsif year
  render(:template => "blog/#{year}/list")
 end
end

def archive
 year = params[:year]
 month = params[:month]
 day = params[:day]
 day = '0'+day if day && day.size == 1
 if (year && month && day)
   @posts_by_month = Blog.find(:all, :conditions => ["year is?", year])
 else
   @posts_by_month = Blog.find(:all).group_by { |post| post.created_at.strftime("%B") }
 end
end

Any help is appreciated.

© Stack Overflow or respective owner

Related posts about ruby-on-rails