Next feature to cross off the TODO-list for blog.rb: tags. It’s now possible to tag posts in the conventional Web 2.0 way. Tags are displayed on top of each post, as links. Click on a tag and You’ll see a list (fetched with Ajax, no less) of posts using that tag.
To get that tag goodness, I’m using the acts_as_taggable_on plugin, which I really recommend! Integrating the plugin in blog.rb was as easy as 1-2-3:
1. Run ./script/generate acts_as_taggable_on_migration to create a migration with the tags and taggings tables. Run the migration (rake db:migrate as usual).
2. Add this line to the Post class:
acts_as_taggable_on :tags
The “:tags” parameter is the name of the tag field in the model. We could have chosen to call it something else, ie “categories”, “keywords”, “topics”, etc, but I’m sticking with “tags” for now.
3. Next we add a field for the tags in the “create post” form:
<p>
<%= f.label :tag_list, "Tags" %><br />
<%= f.text_field :tag_list %>
</p>
That’s it for adding it to the model. Of course, we also want to show the tags in a nice way, and make them useful to readers. This is where The Ajax comes in.
If a post has tags, I display them comma-separated below the title of the post. Each tag in that line is rendered like this:
link_to_remote tag.name,
:url => {:controller => :tags, :action => :show, :id => tag, :blog_id => post.blog, :post_id => post, :show_title => true},
:method => :get,
:update => "post_#{ post.id }_taginfo",
:loading => update_page {|page| page.visual_effect(:fade, "post_#{ post.id }_taginfo", :duration => 0.2)},
:complete => update_page {|page| page.visual_effect(:appear, "post_#{ post.id }_taginfo", :duration => 0.2)}
In the code above, I’m making an ajax call to the standard /tags/{id} REST url. I’m not sure if that’s really kosher, but hey — it’s my app! The result will render a list of linked posts that have that particular tag. Try it out!
Now I’m going to go back and tag all my previous posts! Fun, fun, fun!