Skip to content

Tag, TagCategory & Tagging ​

The taxonomy models, installed by the taxonomies generator. Make any model taggable with the Taggable concern.

Tag ​

ColumnTypeNotes
keystringrequired, unique within its category, or among the tags without one
namestringrequired display name
category_idbigintoptional TagCategory
positionintegerordering within the category
taggings_countintegercounter cache
  • belongs_to :category, has_many :taggings, and taggables, the tagged records of any model
  • Scopes: ordered, in_category(key), in_categories(keys)

Two categories may share a key: a Colors category and a Fruits category can both have an orange tag. The model validates the rule, and the database holds it too, with a unique index on category_id and key, plus one on key for the tags without a category (in a unique index, NULLs never collide).

TagCategory ​

ColumnTypeNotes
keystringrequired, unique
namestringrequired display name
positionintegerordering
tags_countintegercounter cache
  • has_many :tags (ordered). A category can't be deleted while it has tags: left without a category, their keys could collide with others'. Move or delete them first; the admin says so.
  • Scopes: ordered, with_tags

Tagging ​

The polymorphic join between a Tag and any taggable record, unique per (taggable, tag) pair, with counter caches on both sides.

ruby
class Article < ApplicationRecord
  include Trek::Taggable
end

article.tags << Tag.in_category("topics").first
article.tag_names # => ["Ruby"]

Released under the MIT License.