5

從Rails的協會指導,他們表現出許多一對多使用的has_many關係:通過像這樣:添加和從移除的has_many:通過關係

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

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

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

我將如何創建和刪除的約會呢?

如果我有一個@physician,我是否可以寫下如下內容來創建約會?

@patient = @physician.patients.new params[:patient] 
@physician.patients << @patient 
@patient.save # Is this line needed? 

如何刪除或銷燬代碼?另外,如果患者不再存在於約會表中,它會被摧毀嗎?

回答

7

在你創建預約代碼,不需要第二線,並使用#build方法,而不是#new

@patient = @physician.patients.build params[:patient] 
@patient.save # yes, it worked 

摧毀預約記錄,你可以簡單地發現並摧毀:

@appo = @physician.appointments.find(1) 
@appo.destroy 

如果你想與破壞病人一起摧毀預約記錄,你需要添加:依賴設置HAS_MANY:

class Patient < ActiveRecord::Base 
    has_many :appointments 
    has_many :physicians, :through => :appointments, :dependency => :destroy 
end 
+1

謝謝,我認爲刪除約會也會將病人從病人身上移走,反之亦然? – dteoh 2010-12-11 07:17:15

+1

不,它不會,除非你添加':dependency =>:destroy'到'belongs_to'。 – Kevin 2010-12-11 07:25:24

+0

實際上,':dependency'設置只是簡單地爲模型添加一個before_destroy鉤子。如果沒有這個,在銷燬模型記錄時不會有其他模型受到影響。 – Kevin 2010-12-11 07:28:54