Easily maintain a collection of Tag
instances with aggregate counts from your model's tags
.
This gem supports Mongoid 3, Mongoid 4 and Mongoid 5.
Add mongoid-tag-collectible
to your Gemfile.
gem 'mongoid-tag-collectible'
class Thing
include Mongoid::Document
include Mongoid::TagCollectible::Tagged
end
thing1 = Thing.create!(tags: [ 'funny', 'red' ])
thing2 = Thing.create!(tags: [ 'funny', 'yellow' ])
funny_tag = ThingTag.find('funny') # find by tag
funny_tag.name # "funny"
funny_tag.count # 2, not a database query
funny_tag.tagged # thing1 and thing2
You can rename a tag, which causes all the tags in your model's tags
collection to be renamed.
ThingTag.find('funny').update_attributes!(name: 'sad')
Thing.first.tags # [ 'sad', 'red' ]
You can destroy a tag, which also removes it from your model's tags
collection.
ThingTag.find('red').destroy
Thing.first.tags # [ 'sad' ]
Tags are case-sensitive. Transform your tags in before_validation
if you don't want this behavior.
class Thing
before_validation :downcase_tags
private
def downcase_tags
tags = tags.map(&:downcase) if tags
end
end
See CONTRIBUTING.
Copyright Daniel Doubrovkine and Contributors, Artsy Inc., 2013-2015