2017-08-10 23 views
1

爲什麼這個回調Rails中5不停止刪除:Rails的5:防止缺失回調

before_destroy :document_check 

def document_check 
    if documents.present? 
    errors.add(:article, 'in use cannot be deleted') 
    throw :abort 
    end 
end 

This post解釋軌道4和5之間的差異,所以我的回調應防止刪除,如果模型有任何documents ,但我的記錄仍然被刪除。我刪除測試失敗,此錯誤:

TypeError: 
    exception class/object expected 

如何返回一個類或對象與throw :abort聲明?

+1

這個驗證可以在關係定義上完成:'has_many:documents,dependent::restrict' – MrYoshiji

+1

它是Rails 5的':restrict_with_error',但是謝謝!我不知道這個選擇存在。 –

回答