title: rails unique many to many relationship
body: <p>I am using rails 4 and have a many to many relationship using <code>:has_many :through</code> and I am trying to ensure that the join is unique such that a particular film and tag does not join each other more than once. by using <code>validates_uniqueness_of</code> I have achieved this between saves however if two or more of the same tags are added in one update the uniqueness is not ensured. please find below the relevant code:</p>
  
  <pre><code>class Film &lt; ActiveRecord::Base
    has_many :film_tags, inverse_of: :film, dependent: :destroy
    has_many :tags, -&gt; {uniq}, through: :film_tags
  
    accepts_nested_attributes_for :film_tags, allow_destroy: true
  end
  
  class FilmTag &lt; ActiveRecord::Base
    belongs_to :film, inverse_of: :film_tags
    belongs_to :tag, inverse_of: :film_tags, counter_cache: true
  
    validates_uniqueness_of :tag_id, scope: :film_id, message: "duplicate tag"
  end
  
  class Tag &lt; ActiveRecord::Base
    has_many :film_tags, inverse_of: :tag, dependent: :destroy
    has_many :films, -&gt; {uniq}, through: :film_tags
  
    validates_uniqueness_of :name
  end
  </code></pre>
  
  <p>I have tried adding a <code>before_save</code> to film where <code>film.film_tags</code> had <code>.uniq</code> run against it (also tried <code>uniq{|film_tag| film_tag.tag_id}</code>) but this just removes all <code>film_tag</code> joins but 1 even if some tags were not duplicated.</p>
  
  <p>Can anyone provide help with this issue? Alternatively if more information is required please ask.</p>