2012-02-27 35 views
1

如果我有以下的協會......Ruby on Rails 3:如何在不刪除數據庫的情況下斷開對象與其他對象的連接?

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

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

我可以將現有的任命添加到醫生...

appoint = Appointments.find(params[:id]) 
phys = Physician.find(params[:id]) 
phys.appointments << appoint 
phys.save 

,但我無法弄清楚如何刪除約會從醫師名單中刪除而不刪除它。我想在與Physician表斷開連接後將約會保留在約會表中。

非常感謝您的智慧!

回答

3

你就不能設置特別是Appointmentphysician_idnil

+0

這是最簡單的方法。但是從問題來看,他是否想保持參照完整性和/或是否能夠跟蹤一個約會過去曾經聯繫過的醫生。通過將其設置爲空,他會丟失該信息。但也許它確定。這個問題沒有具體說明。 – 2012-02-27 22:14:49

3

你可以使用軟刪除方法:讓另一列爲「刪除布爾值」或「deleted_at datetime」(這一個編碼兩條信息,記錄已被刪除以及何時刪除)。

然後在您所有的疑問,你只需要尊重這一點:... WHERE deleted_at IS NULL

使用Rails,你甚至可以把這個作爲默認爲所有查詢:

class Foo < ActiveRecord::Base 
    default_scope where('deleted_at IS NULL') 
end 
相關問題