title: Uniqueness of has_many association
body: <pre><code>class User &lt; ApplicationRecord
    has_and_belongs_to_many :profiles
  
    def add_profile(profile)
      self.profiles &lt;&lt; profile unless self.profiles.include?(profile)
    end
  end
  
  class Profile &lt; ApplicationRecord
    has_and_belongs_to_many :users
    validates_uniqueness_of :linkedin_id, allow_nil: true
  end
  </code></pre>
  
  <p>For some reason on production I get </p>
  
  <p><code>ActiveRecord::RecordInvalid: Validation failed: Linkedin has already been taken</code> </p>
  
  <p>on </p>
  
  <p><code>self.profiles &lt;&lt; profile unless self.profiles.include?(profile)</code> line.</p>
  
  <p>And after this I have duplicates in User.profiles records.</p>
  
  <p>What is the problem?</p>