lundi 7 septembre 2015

Avoid duplicate entry with has_many through rails

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?

Aucun commentaire:

Enregistrer un commentaire