Fast and Easy Archives in Rails

In building this site, I needed to create some kind of archiving system for my articles. I was looking for a simple solution, something without having to write a bunch more code. Search results were surprisingly limited. This tutorial sounded like just what I needed. But did I really have to do all that. I needed something simpler. The answer was right there sitting in my app all along.

Acts_as_Taggable_on is a great plugin that I already had in place for my article and project categories and tags. Get it. You will be using this to set up your archives. Installation and usage directions on the site are very straightforward. In fact, as you review the directions you should begin to see how we can implement this for archiving. So let's begin.

First, install the plugin:

script/plugin install \
git://github.com/mbleigh/acts-as-taggable-on.git

Now we need to run the migration script:

script/generate acts_as_taggable_on_migration
rake db:migrate

This will create the necessary tables and fields in the database. Now open up your model and add the line:

acts_as_taggable_on :archives

You can just add it to any existing tags you may have.

Now we need a way to set the contents of your model's 'archive_list', to that of its 'created_at' attribute. Add this to your model:

def make_archive
  self.archive_list = self.created_at.to_formatted_s(:clean)
end

To make this work, I use the ActiveRecord 'after_create' callback on the model. Add this somewhere at the top of your model:

after_create :make_archive

Now, whenever you create a post, rails will populate your archive_list with that date. You should format it so your achive list won't be filled with the full time stamp, which is what this does:

self.created_at.to_formatted_s(:clean)

You can also change what the archive_list is populated with. For example, if you have a "published_on" feature.

This is just an easy way to make archives for you models. I haven't run across any issues, and it does just what I need it to do.