0

I have been using this nested attributes with has_many :through

class Check < ActiveRecord::Base
  has_many :checks_tags, dependent: :destroy
  has_many :tags, through: :checks_tags

  attr_accessible :tags_attributes, :checks_tags_attributes
  accepts_nested_attributes_for :tags, :checks_tags
end 

class Tag < ActiveRecord::Base
  has_many :checks_tags, dependent: :destroy
  has_many :checks, through: :checks_tags  
end

class CheckTag < ActiveRecord::Base
  belongs_to :check
  belongs_to :tag
end

so here the issue is when i create with this hash

"tags_attributes"=>[{"id"=>"", "name"=>"test12", "company_id"=>"1"}, {"id"=>"", "name"=>"test12", "company_id"=>"1"}]

actually here have two tags with same name, so its creating Tag twice and after putting twice on CheckTag, so is there any way to avoid this creation as twice in Tag?

Developer
  • 561
  • 7
  • 29

1 Answers1

0

If you want it forbidden in the database, you could create a unique index on the combination of the two columns on the check_tag table. If you want to handle it in rails, you can do it with a before_save callback on the Check model (if that's the only way you create these), but that may make you vulnerable to a race condition.

See this answer: Index on multiple columns in RoR

Community
  • 1
  • 1
Daiku
  • 1,237
  • 11
  • 20