|
# frozen_string_literal: true |
|
|
|
# Tag ownership example using easy_tags |
|
|
|
require "bundler/inline" |
|
|
|
gemfile(true) do |
|
source "https://rubygems.org" |
|
gem "activerecord", "~> 7.0" |
|
gem "sqlite3" |
|
gem "easy_tags", "~> 0.2.8" |
|
end |
|
|
|
require "active_record" |
|
require "minitest/autorun" |
|
require "logger" |
|
|
|
# This connection will do for database-independent bug reports. |
|
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") |
|
ActiveRecord::Base.logger = Logger.new(STDOUT) |
|
|
|
ActiveRecord::Schema.define do |
|
create_table :tags do |t| |
|
t.string :name, index: true |
|
|
|
t.timestamps null: false |
|
end |
|
|
|
create_table :taggings do |t| |
|
t.references :tag, foreign_key: { to_table: :tags }, null: false, index: true |
|
t.references :taggable, polymorphic: true, index: true, null: false |
|
t.string :context, null: false, index: true |
|
|
|
t.datetime :created_at, null: false |
|
end |
|
|
|
create_table :accounts do |t| |
|
t.string :name |
|
end |
|
|
|
create_table :tag_ownerships do |t| |
|
t.references :tag |
|
t.references :account |
|
end |
|
|
|
add_index :tag_ownerships, [ :tag_id, :account_id ], :unique => true |
|
end |
|
|
|
class TagOwnership < ActiveRecord::Base |
|
belongs_to :tag, class_name: 'EasyTags::Tag' |
|
belongs_to :account |
|
|
|
validates_uniqueness_of :tag_id, scope: :account_id |
|
end |
|
|
|
class Account < ActiveRecord::Base |
|
include EasyTags::Taggable |
|
easy_tags_on( |
|
account_tags: { after_add: :add_ownership } |
|
) |
|
|
|
has_many :tag_ownerships |
|
has_many :owned_tags, through: :tag_ownerships, source: :tag |
|
|
|
private |
|
|
|
def add_ownership(tagging) |
|
TagOwnership.create!(tag: tagging.tag, account: self) |
|
rescue ActiveRecord::RecordNotUnique, SQLite3::ConstraintException => _e |
|
# do nothing: already exists |
|
end |
|
end |
|
|
|
class OwnershipTest < Minitest::Test |
|
def test_validation |
|
account1 = Account.create(name: 'account_1') |
|
account2 = Account.create(name: 'account_2') |
|
|
|
account1.account_tags = %w[foo bar] |
|
account2.account_tags = %w[foo baz] |
|
|
|
account1.save! |
|
account2.save! |
|
|
|
assert account1.owned_tags.map(&:name) == %w[foo bar] |
|
assert account2.owned_tags.map(&:name) == %w[foo baz] |
|
end |
|
end |