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 end
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 .input-row = f.label :tags = f.text_field :tag_list .input-row = f.label :topics = f.text_field :topics_list
Then attach the
select2 plugin to the form elements. Make sure you’ve got
select.js included on the page.
If you haven’t found it, there’s a nice package that puts select2 in the asset pipeline – https://github.com/argerim/select2-rails.