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?
如何刪除或銷燬代碼?另外,如果患者不再存在於約會表中,它會被摧毀嗎?
謝謝,我認爲刪除約會也會將病人從病人身上移走,反之亦然? – dteoh 2010-12-11 07:17:15
不,它不會,除非你添加':dependency =>:destroy'到'belongs_to'。 – Kevin 2010-12-11 07:25:24
實際上,':dependency'設置只是簡單地爲模型添加一個before_destroy鉤子。如果沒有這個,在銷燬模型記錄時不會有其他模型受到影響。 – Kevin 2010-12-11 07:28:54