---
url: /reference/models/tag.md
---
# Tag, TagCategory & Tagging

The taxonomy models, installed by the [taxonomies generator](/reference/generators/taxonomies). Make any model taggable with the [Taggable](/reference/concerns/taggable) concern.

## Tag

| Column | Type | Notes |
| --- | --- | --- |
| `key` | string | required, unique within its category, or among the tags without one |
| `name` | string | required display name |
| `category_id` | bigint | optional [TagCategory](#tagcategory) |
| `position` | integer | ordering within the category |
| `taggings_count` | integer | counter 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

| Column | Type | Notes |
| --- | --- | --- |
| `key` | string | required, unique |
| `name` | string | required display name |
| `position` | integer | ordering |
| `tags_count` | integer | counter 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"]
```
