How to do tagging in Rails with gem ‘Acts_as_taggable_on’

How to do tagging in Rails with gem ‘Acts_as_taggable_on’

2 Minutes Read

ror41Tagging 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:


  • Add the gem to your Gemfile:
  • gem ‘acts-as-taggable-on'
  • Then run the bundle
  • bundle install


  • Run the generator command
  • rails g acts_as_taggable_on:migration
  • Run the migration file
  • rake db:migrate

    This migration will create two tables in the database: tags and taggings.
    Now you have to modify your model where you want to implement tagging.
    For example, we like to implement the tagging on Post model.

  • Add the following codes to the “Post” model to have acts_as_taggable and also add a “tag_list” field to the attr_accessible list.
  • attr_accessible :content, :name, :tag_list


  • Add a new field to your post form.
  • <%= f.label :tag_list, "Tags (separated by commas)" %>
    <%= f.text_field :tag_list %>


  • Add the following codes, if you want to show the tags for the tagged posts in the listing page:
  • <% @posts.each do |post| %>
    <h2><%= link_to, post %></h2>
    <%= simple_format post.content %>
    Tags: <%= raw { |t| link_to t, tag_path(t) }.join(', ') %>
    <% end %>


  • Modify your route file to get the tags
  • get 'tags/:tag', to: 'posts#index', as: :tag


  • Modify your controller:
  • class PostsController < ApplicationController
    def index
    if params[:tag]
    @posts = Post.tagged_with(params[:tag])
    @posts = Post.all

Voila! You have done it.

Jayadev Das

Do what you do best in – that’s what I’ve always believed in and that’s what I preach. Over the past 25+ years (yup that’s my expertise ‘n’ experience in the Information Technology domain), I’ve been consulting to small, medium and large companies ‘bout Web Technologies, Mobile Future as well as on the good-and-bad of tech. Blogger, International Business Advisor, Web Technology Expert, Sales Guru, Startup Mentor, Insurance Sales Portal Expert & a Tennis Player. And top of all – a complete family man!

No Comments

Post A Comment

Exit pop up

Before You Go...!

Subscribe to Andolasoft Blog

Stay up to date with the latest techniques of web & mobile app development service tips and our SaaS and open source product news.
Holler Box