Create a Blog Archive with Rails

Handwritten by TVD

Creating an archive for your blog posts can be fun. But first, you’ll have to understand ActiveRecord’s group_by method.

Previously, I wrote about SEO Friendly URLs in Rails. Having a well-formed archive helps with SEO by creating a centralized location for all your Google Bot slugs.

Creating a Google Sitemap for your Rails blog is another good SEO step to consider. Showing Google where to find your posts is wise Rails-fu and will set the stage for your blog’s archive.

Rails ActiveRecord Group_By

Learning to group a collection of your posts by month can be confusing at first. Using Rails’ ActiveRecord group_by method is the key to success here. Let’s get started:

####app/controllers/archives_controller.rb

def index
@posts = Post.all(:select => "title, id, posted_at", :order => "posted_at DESC")
@post_months = @posts.group_by { |t| t.posted_at.beginning_of_month }
end

The code gets your collection of posts. Then it gets each post’s corresponding post date.

Also, notice the code brings back only the data needed instead of the entire object graph. This decreases latency and thus, increases speed.

Another feature of this code is I’m grouping by month. Now, this may sound more purpose than feature, but it actually means something significant. Grouping by month ensures the list is chronological, even when a new year starts.

####app/views/archives/index.html.erb

<div class="archives">
<h2>Blog Archive</h2>

<% @post_months.sort.reverse.each do |month, posts| %>
<h3><%=h month.strftime("%B %Y") %></
h3>
<ul>
<% for post in posts %>
<li>
<%=h link_to post.title, post_path(post) %></li>
<% end %>
</ul>
<% end %>
</div>

This will display a month, then list each blog post for that month. When complete, it will list the next month, etc. Initially, your posts will display from oldest to newest. If that’s what you want, then you’re done.

But, if you’re like me, you want to display your blog archive posts from newest to oldest. To accomplish this, you need to reverse your collection using Ruby’s reverse string function.

That’s it! Good luck and happy coding!

discuss on twitter


every day thousands of developers use our charts & gauges to get the job done right

JavaScript Charts JavaScript Gauges JavaScript Flight Gauges


← return to all articles