title: How to avoid creating duplicate records in join table with has_many through association?
body: <p>I have two models <code>Physician</code>, <code>Patient</code> and a join model <code>Appointment</code> and the association is like as follows:</p>
  
  <pre><code>class Physician &lt; ActiveRecord::Base
    has_many :appointments
    has_many :patients, through: :appointments
    accepts_nested_attributes_for :patients
  end
  
  class Patient &lt; ActiveRecord::Base
    has_many :appointments
    has_many :physicians, through: :appointments
    accepts_nested_attributes_for :appointments
  end
  
  class Appointment &lt; ActiveRecord::Base
    belongs_to :physician
    belongs_to :patient
  end
  </code></pre>
  
  <p>I want to update <code>appoinment_data</code> in the <code>appointment</code> table when there is a new 
  entry in the <code>appointment</code> table.</p>
  
  <p>So in the rails console:</p>
  
  <pre><code>a = Physician.last
  #&lt;Physician id: 1, name: "Hamza", address: "Pune", created_at: "2017-02-22 07:07:10", updated_at: "2017-02-22 07:07:10"&gt;
  
  a.update(patients_attributes: [{ name: 'Prajakta', disease: 'Fever', appointments_attributes: [{appointment_data: DateTime.now}]}])
     (0.7ms)  BEGIN
    SQL (0.9ms)  INSERT INTO "patients" ("name", "disease", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  [["name", "Prajakta"], ["disease", "Fever"], ["created_at", "2017-02-22 08:30:22.321863"], ["updated_at", "2017-02-22 08:30:22.321863"]]
    SQL (0.8ms)  INSERT INTO "appointments" ("appointment_data", "patient_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  [["appointment_data", "2017-02-22 08:30:22.311198"], ["patient_id", 5], ["created_at", "2017-02-22 08:30:22.326373"], ["updated_at", "2017-02-22 08:30:22.326373"]]
    SQL (0.9ms)  INSERT INTO "appointments" ("physician_id", "patient_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  [["physician_id", 1], ["patient_id", 5], ["created_at", "2017-02-22 08:30:22.333624"], ["updated_at", "2017-02-22 08:30:22.333624"]]
     (1.2ms)  COMMIT
  =&gt; true
  </code></pre>
  
  <p>It is creating two <code>records</code> in the <code>appointment</code> table.
  One record with <code>appointment_data</code> and <code>patient_id</code>. Other is with <code>physician_id</code> and <code>patient_id</code>.</p>
  
  <p>What am i missing here? </p>