I have a Tag model with only one attribute: :name.
tag.rb:
class Tag < ActiveRecord::Base
has_many :taggings, :dependent => :destroy
has_many :posts, :through => :taggings
has_many :subscriptions
has_many :subscribed_users, :source => :user, :through => :subscriptions
end
(it has a many-to-many relationship with a Post model):
class Post < ActiveRecord::Base
attr_accessible :title, :content, :tag_names
validates :title, :presence => true,
:length => { :maximum => 30 },
:uniqueness => true
validates :content, :presence => true,
:uniqueness => true
has_many :taggings, :dependent => :destroy
has_many :tags, :through => :taggings
attr_writer :tag_names
after_save :assign_tags
def tag_names
@tag_names || tags.map(&:name).join(' ')
end
private
def assign_tags
if @tag_names
self.tags = @tag_names.split(" ").map do |name|
Tag.find_or_create_by_name(name)
end
end
end
end
As you can imagine I don’t want to have 2 tags with the same name. Right now, it is possible to create them. If there is a tag like this: <Tag id=1, name=food> and later another tag like this is created: <Tag id=2, name=food>. I want the second to be ignored because there is already a tag with the name food.
(Pretty much how all tag systems works)
Any suggestions in order to accomplish this?
I am not sure if I completely understand your problem but maybe this will be helpful for you.
…