-
Open your Gemfile, add the following
gem ‘acts-as-taggable-on’, ‘~> 2.3.1’
-
Open your terminal, navigate to your application, and run:
bundle install
followed by
rails generate acts_as_taggable_on:migration
and finally
rake db:migrate
-
Detect a model you want to add tags to (in my case, post.rb), and add a line just like this:
acts_as_taggable_on :tags
Then in posts_helper.rb add
include ActsAsTaggableOn::TagsHelper
-
We then need to add a way to add tags in our posts, so let’s edit the posts/_form.html.erb file, and at the end of our form (and before the submit button) let’s add:
<%= f.label :tags %> <%= f.text_field :tag_list %>
-
Now we have to edit our view. In your posts/show.html.erb file, where you want to show the tags, add:
<% @post.tags.any? %>
<% @post.tags.each do |tag| %> <%= link_to tag.name, tagged_url(:tag => tag.name) %>
<% end %>
meaning that unless there are no tags, the tags should be shown. Please note that “tagged” is the name of an action within our posts controller, and we are going to add it in our next step.
-
Modify your posts controller
In the posts controller you need to add a new action which we can call tagged. This is the action we are going to show when a user clicks on a tag in our posts, so if you prefer you can call it whatever you like, but if you do, remember to change it in the steps above too.
def tagged
if params[:tag].present? @posts = Post.tagged_with(params[:tag]) else @posts = Post.postall end
end
This little code above would grab the tag value we are passing to the controller (if present), and would put it into the instance variable @posts. More in detail, this line: @posts = Post.tagged_with(params) means: @posts will contain posts tagged with the tag parameter, quite self explainatory I believe.
-
Create a view for our Tagged action, which can be exactly the same as your index view (mine is, except for the title), and add a route to reach it in your routes.rb file, like so:
match ‘tagged’ => ‘posts#tagged’, :as => ‘tagged’
Please note that tagged_with is a functionality provided by the gem acts_as_taggable_on.