For instance, in a social network, a user might have tags that are called skills, interests, sports, and more. This article will show you how to implement tagging in your Rails application. Let’s run through this with me.
Installation
Add gem acts-as-taggable-on
to your Gemfile:
1
|
|
and run bundle:
1
|
|
install migrations:
1 2 |
|
This creates some tables and doesn’t need to know anything specific about your models. The models and concerns for working with these tables (Tag, Tagging, etc).
Model Integration
1 2 3 |
|
Now you can do, eg:
1 2 3 4 |
|
#tag_list=
takes a string and splits it up, using the resulting substrings to find_or_create Tags, and associate them with the taggable thing (eg, Post
), through Taggings
. You don’t need to know this.
The important thing is that, with #tag_list=
we can manage tags via a comma-separated-list in a text field in a form.
Controller Integration
1 2 3 4 5 6 7 8 9 10 |
|
This is assuming you’re trying to tag an existing Post
model with title
and body
fields, web-accessible through an existing PostsController
, with index
, show
, new
, etc. methods.
Substitute your own, the important machinery here is whitelisting tag_list
from the params
.
Form Integration
1 2 3 4 5 6 |
|
Now you can create tags for stuff. How about displaying them? Couple options, I’ll go through the most explicit (a TagsController
with index and show actions), but they can be rolled up into other controllers/actions.
Controller
1 2 3 4 |
|
1 2 3 4 5 6 7 8 9 10 |
|
It’s unfortunate we have to do this slightly awkward workaround with Post.tagged_with(@tag.name)
in tags#show
. The ActsAsTaggableOn::Tag
model does not have a built-in relationship with its taggable types (this is a necessary consequence of some polymorphism which we’re not using here). We could add one for Post
, but this way is easier to demonstrate.
Tags Views
1
|
|
1 2 |
|
1 2 |
|
Note the partial path is acts_as_taggable_on/tags/tag
. This is so we can just say render @tags
and let rails do its implicit magic. There are other ways to organize everything, but this is the simplest.
View Integration
1 2 |
|
1 2 |
|
1 2 3 |
|
And that should be it. It’ll look shitty, but I hope you can figure out how to elaborate on this once you have it working. If anything here is assuming familiarity with something you don’t have, ask and I will gladly elaborate.
So far so good, That’s it!!! See ya!!! :)