2017-02-22 115 views
1

我有兩個型號PhysicianPatient和聯接模型Appointment和協會就像如下:如何避免通過關聯在has_many連接表中創建重複記錄?

class Physician < ActiveRecord::Base 
    has_many :appointments 
    has_many :patients, through: :appointments 
    accepts_nested_attributes_for :patients 
end 

class Patient < ActiveRecord::Base 
    has_many :appointments 
    has_many :physicians, through: :appointments 
    accepts_nested_attributes_for :appointments 
end 

class Appointment < ActiveRecord::Base 
    belongs_to :physician 
    belongs_to :patient 
end 

我想在appointment表更新appoinment_data時,有在appointment表中的新 條目。

所以在軌控制檯:

a = Physician.last 
#<Physician id: 1, name: "Hamza", address: "Pune", created_at: "2017-02-22 07:07:10", updated_at: "2017-02-22 07:07:10"> 

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 
=> true 

它在appointment表中創建兩個recordsappointment_datapatient_id的一條記錄。其他與physician_idpatient_id

我在這裏失蹤了什麼?

回答

0

我找到了一個解決方法,放置accepts_nested_attributes_for。我現在聯想是這樣的:

class Physician < ActiveRecord::Base 
    has_many :appointments 
    has_many :patients, through: :appointments 
    accepts_nested_attributes_for :appointments 
end 

class Patient < ActiveRecord::Base 
    has_many :appointments 
    has_many :physicians, through: :appointments 
end 

class Appointment < ActiveRecord::Base 
    belongs_to :physician 
    belongs_to :patient 
    accepts_nested_attributes_for :patients 
end 

我在控制檯這樣做:

a = Physician.last 
a.update(appointment_attributes: [{appointment_data: DateTime.now, patient_attributes: {name: 'Rajesh', disease: 'fever'}}]) 

它現在在appointments表只創建一個記錄。

相關問題