HasTags
HasTags is a lightweight library for easily adding tags to your ActiveRecord models.
Installation
Add this line to your application's Gemfile:
gem 'has_tags'
And then execute:
$ bundle
Or install it yourself as:
$ gem install has_tags
Usage
First, you must run rails g has_tags:install
to install the tag migrations.
Once the migrations are installed, run rake db:migrate
.
Now choose a model to add tags to. Let's use Post
as an example. All you have to do is add has_tags
to the model class definition:
class Post < ActiveRecord::Base
end
Your post class can now have associated tags.
To set tags on a Post
instance, whitelist the tag_list
parameter in your controller:
class PostController < ActiveRecord::Base
# ...
private
def post_params
params.require(:post).permit(:param1, :param2, :tag_list)
end
end
tag_list
should be a string with tags separated by commas, or colons to make a context tag.
Examples
For creating top-level tags, a user can type in tags only separated by commas:
"Sports, Food"
For creating tags within tags, where to top-level tag acts as the context or parent for the child tag, separate the tags by colons:
"Sports:Hockey, Food"
This creates three tags: Sports, Hockey and Food. Sports is now the context in which Hockey lives. Now we can call:
context = Tag.find_by(name: "Sports")
context. # => Hockey tag
The context tag syntax can be nested like so:
"Sports:Hockey:Strategy"
strategy = Tag.find_by(name: "Strategy")
hockey = strategy.context # => Hockey tag
hockey.context # => Sports tag
Contributing
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create new Pull Request