Taggable Mongoid Models

I was looking for a simple way to add tagging to my Mongoid 3+ models and most of the options I found were for Mongoid 2 only. Luckily I stumbled upon Mongoid Simple Tags from Mauro Torres(chebyte) a ruby gem that supports Mongoid 3+.

Its a nice simple way to add tagging. Simply include “Mongoid::Document::Taggable” to your model.

1
2
3
4
class User
  include Mongoid::Document
  include Mongoid::Document::Taggable
end

Once added you can assign tags through the #tag_list= method. This assumes a string of comma seperated tags, which are then stored in the tags field as an array.

1
u = User.create(:name => "Tuquito", tag_list: "linux, tucuman, free software")

You can retrieve back comma seperated list of tags with the #tag_list method or an array of tags on the object with the #tags method.

1
2
User.tag_list #=>["free software", "linux", "tucuman"]
u.tags     # => ["linux","tucuman","free software"]

Mongoid-simple-tags provides a way to search for instances with a tag via the ::tagged_with method. This can either be given a single tag or an array of tags. In the later case it will return all instance that have any of the given tags. Unfortunately there is not currently a method to search for instances matching all tags in an array.

1
2
User.tagged_with("linux") # => u
User.tagged_with(["tucuman", "free software"]) # => u

You can also get a list of all tags used on a model with there associated counts, with the ::all_tags method. This is accomplished using MongoDb’s map-reduce functions.

1
2
3
# using map-reduce function

User.all_tags #=>[{:name=>"free software", :count=>1}, {:name=>"linux", :count=>2}, {:name=>"tucuman", :count=>1}]

Lastly, if you simply would like an array of all tags used on instances of a model there is the ::tag_list method.

1
User.tag_list #=>["free software", "linux", "tucuman"]

Comments