2016-06-14 52 views

回答

17

您應該返回false

Rails的5

「取消回調

如果before_ *回調拋出:中止,所有後來的回調和相關動作被取消。」

軌道4,下

「取消回調

如果before_ *回調返回false,所有後來的回調和相關動作被取消。回調通常是在順序運行它們被定義,在模型中被定義爲方法的回調的例外,這被稱爲last。「

Source

+4

使用Rails 5,返回false不再起作用。應該拋出(:中止)'以防止刪除記錄。看到[這個評論](http://stackoverflow.com/questions/123078/how-do-i-validate-on-destroy-in-rails#comment59333149_123190) – RFVoltolini

+0

謝謝,我已經更新了我的答案,以幫助新人。 – Leito

+1

感謝您指定:Rails 5的中止技術。應該真的幫助我。 – CanadaIT

2

導軌包裹保存,並在交易破壞,所以在回調raise將工作:

class Post < ActiveRecord::Base 
    before_destroy :saveable? 

    def saveable? 
    if true 
     raise "Destroy aborted; you can't do that!" 
    end 
    end 
end 

替代true你的病情。

下面是刪節控制檯輸出:

[1] pry(main)> Post.first.id 
=> 1 
[2] pry(main)> Post.first.destroy 
RuntimeError: Destroy aborted; you can't do that! 
[3] pry(main)> Post.first.id 
=> 1 

Documentation

+0

thnks,但不希望它引發任何事情......什麼都不做 –

+0

有道理。因爲這是'before_ *'回調函數,所以'raise'或'false'都可以。 「提升」的好處是你會得到一個明確的信息,你可以在日誌中追蹤,而不是「摧毀」悄悄地沒有發生。選擇哪個取決於您的失敗情況可能會如何意外。 –

+1

在Rails 5中,你將不得不明確地提出:中止。你現在可以開始了。 – mwoods79

1

您也可以覆蓋#destroy方法:

def destroy 
    study_assignments.empty? ? super : self 
end