Tagging is a way to give a keyword and search by that particular keyword. In Rails “acts-as-taggable-on” is one of the popular gem for tagging. With ‘acts_as_taggable_on’, you can tag a single model on several contexts, such as skills, interests, and awards
Below is an example to describe how to implement it in a Rails application:
-
Step#1
- Add the gem to your Gemfile:
gem ‘acts-as-taggable-on'
bundle install
Step#2
rails g acts_as_taggable_on:migration
rake db:migrate
This migration will create two tables in the database: tags and taggings.
Step#3
Now you have to modify your model where you want to implement tagging.
For example, we like to implement the tagging on Post model.
attr_accessible :content, :name, :tag_list acts_as_taggable
Step#4
<%= f.label :tag_list, "Tags (separated by commas)" %> <%= f.text_field :tag_list %>
Step#5
<% @posts.each do |post| %> <h2><%= link_to post.name, post %></h2> <%= simple_format post.content %> <p> Tags: <%= raw post.tag_list.map { |t| link_to t, tag_path(t) }.join(', ') %> </p> <% end %>
Step#6
get 'tags/:tag', to: 'posts#index', as: :tag
Step#7
class PostsController < ApplicationController def index if params[:tag] @posts = Post.tagged_with(params[:tag]) else @posts = Post.all end end end
Voila! You have done it.