我有兩個模型與多對多關聯到第三個模型。 由前:Rails 4協會驗證破壞
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
而且使用simple_form我有這個複選框設置(醫師形式):
...
= f.association :patients, as: :check_boxes
...
當我查了一些複選框,保存後的軌道將在數據庫中創建約會。
當我取消選中複選框時,導軌將銷燬一些未經檢查的約會。
所以更新將EQ到
physician.patient_ids = []
我想驗證約會之前刪除。例如,如果約會有一些警告,我想在保存Physician表單時顯示警報驗證錯誤。
所以,我想,也許軌將調用destroy方法上的約會,並試圖:
class Appointment < ActiveRecord::Base
before_destroy :check_destroy
private
def check_destroy
raise 'you can not do it!'
end
不,導軌只是刪除約會從節省醫師數據庫。
也許rails會使用delete方法嗎?然後我試過這個:
class Appointment < ActiveRecord::Base
def delete
raise 'you can not do it!'
end
不,再次。
似乎rails只是直接從數據庫中刪除連接關聯(約會)。
如何預防?我想驗證在保存醫師之前將被刪除的所有約會,並且如果某些約會無法刪除,則向醫師添加錯誤。
是否有任何在以下崗位工作的方法是什麼? http://stackoverflow.com/questions/123078/how-do-i-validate-on-destroy-in-rails – rodamn
@rodamn如果我呼籲摧毀醫生,我認爲這將作品相關的:破壞。但在我的情況下,我不會調用銷燬,而只是在控制器#update action中使用一組ID來調用保存模型。 –