acts_as_taggable_on + select2 = Super Easy Tags in Rails

I’ve had two projects in the past little bit where I wanted user input tags for objects. I also wanted to have typed tags – tags of different categories applied to the same object. I found that acts_as_taggable_on (Rails gem) and select2 (jQuery plugin) work really nicely together and make this an easy task.

Let’s assume that we have an ActiveRecord model for a Post. Follow directions to install acts_as_taggable_on (add to Gemfile, initialize and run migration). Then add two different tag types to Post like this:

class Post < ActiveRecord::Base
  acts_as_taggable # basic usage - gives us 'tags'
  acts_as_taggable_on :topics

With this, the Post model is ready to store tags and topics.

irb> Post.first.tags << 'super fun'

To push this to the users, we want a nice UI for users to enter tags/topics. This is where Select2 comes in. In your form for adding/editing posts, add two input boxes, one for topics and one for tags

# using haml templating
  = f.label :tags
  = f.text_field :tag_list
  = f.label :topics
  = f.text_field :topics_list

Then attach the select2 plugin to the form elements. Make sure you’ve got jQuery and select.js included on the page.

// in your javascript
$(function() {
  $('.input-row #post_topics_list, .input-row #post_tags_list').select2({tags:[]})

And you get a beautiful input box with handy tag handling.
Tags and Topics form

If you haven’t found it, there’s a nice package that puts select2 in the asset pipeline –


One thought on “acts_as_taggable_on + select2 = Super Easy Tags in Rails

Leave a Reply

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

You are commenting using your 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