Reputation: 1162
I have this system essentially:
class Article < ApplicationRecord
has_many :tag_associations
has_many :tags, through :tag_associations
end
class Tag < ApplicationRecord
# attr :name
end
How do I make it so the article can only have one of each tag name? That is, say I have these tags:
{ name: 'foo' }
{ name: 'bar' }
{ name: 'baz' }
I would eexpect this to be the final result:
tag1 = Tag.create!(name: 'foo')
tag2 = Tag.create!(name: 'bar')
tag3 = Tag.create!(name: 'baz')
article.tags << tag1
article.tags << tag2
article.tags << tag1
article.tags << tag1
article.tags << tag1
article.save!
article.tags # => [tag1, tag2]
How do I achieve this? I am not highly familiar with Rails paradigms, and am not really sure how to do this in a general way even with plain SQL. But I am just looking for how to do this the Rails way.
Upvotes: 0
Views: 75
Reputation: 6156
It's done using an ActiveRecord uniqueness validation.
In this case, I would suggest that the validation should be applied in the ArticleTag
model. Create this model if you don't already have it.
class ArticleTag < ActiveRecord::Base
validates :tag_id, :uniqueness, scope: :article_id
end
This says that instances of ArticleTag with associated with a given Article should have unique tag_id. So if you try to create a duplicate tag for an articl, you'll raise a validation error.
Upvotes: 1