TagColumns
Fast & simple Rails ActiveRecord model tagging using PostgreSQL's Array datatype. Similar to acts_as_taggable_on but lighter weight with fewer features. Also, be sure to check out acts_as_taggable_array_on.
Use Cases
Assign categories to your database records.
- Assign multiple groups to user records
- Assign categories to blog posts et al.
- etc...
Quick Start
# Gemfile
gem "tag_columns"
# db/migrate/TIMESTAMP_add_groups_to_user.rb
class AddGroupsToUser < ActiveRecord::Migration[5.0]
def change
add_column :users, :groups, :string, array: true, default: [], null: false
add_index :users, :groups, using: "gin"
end
end
# app/models/user.rb
class User < ApplicationRecord
include TagColumns
tag_columns :groups
end
user = User.find(1)
# assigning tags
user.groups << :reader
user.groups << :writer
user.save
# checking tags
is_writer = user.has_group?(:writer)
is_reader_or_writer = user.has_any_groups?(:reader, :writer)
is_reader_and_writer = user.has_all_groups?(:reader, :writer)
# finding tagged records
assigned = User.with_groups
unassigned = User.without_groups
writers = User.with_any_groups(:writer)
non_writers = User.without_any_groups(:writer)
readers_or_writers = User.with_any_groups(:reader, :writer)
readers_and_writers = User.with_all_groups(:reader, :writer)
non_readers_and_writers = User.without_all_groups(:reader, :writer)
# find unique tags across all users
User.unique_groups
# find unique tags for users with the last name 'Smith'
User.unique_groups(last_name: "Smith")