I am a newbie to rails. Today I met a problem to save associated models.
I have 2 models with the following association, The Tag model has a validation role for attribute 'name' to be uniqueness.
class Product < ActiveRecord::Base
has_and_belongs_to_many :tags
validates_associated :tags
end
class Tag < ActiveRecord::Base
has_and_belongs_to_many :products
validates :name, :presence => true, :uniqueness => true
end
What I want to archive is to create a product object with association to several tags. I used the function below:
def self.create_with_tags(value)
tags = []
if value.has_key? :tags
tags = value[:tags]
value.delete :tags
end
p = Product.new(value)
tags.each do |tag|
p.tags.build(:name => tag)
end
p.save!
p
end
The test code is
p = Product.create_with_tags(:name => 'test product', :status => true, :tags =>['tag1','tag2','tag3','tag4'])
The test code works fine when the tag names ['tag1','tag2','tag3','tag4'] does not exist in database ; if one of the tags already exists in database, for example, 'tag1', then the association validation will fails and the whole creation process rollback.
What I want to archive is: in case some of the tags already exists in database, the validation don't fails, instead, existing tag is found (but not created) and the association between product and existing tags are created. for example, if 'tag1' already in database, it won't be created again , but the association in products_tags table is created.