如何解決after_save回調中生成的錯誤,然後最終將其顯示給用戶?在我的模型代碼看起來是這樣的:Rails:向after_save回調中產生的用戶顯示錯誤
Class MyModel
after_save :call_other_class_responsible_for_parsing
def call_other_class_responsible_for_parsing
# this method is used by multiple models
ModelTwo.parse_css
end
end
在我的控制,我現在將用戶重定向的其他地方,如果升級成功,但是,我認爲更新是成功的,如果它通過了所有現有的驗證的和回調中沒有錯誤(來自Less :: Parser)。
編輯:
我混淆了我的想法在我原來的問題。 MyModel從相應的控制器中獲取,然後從模型中運行after_save回調。在call_other_class_responsible_for_parsing裏面,有一個對另一個模型的調用,比如ModelTwo,它可以進行Less解析。我一直在使用這樣的代碼嘗試:
def self.parse_css
@my_model = MyModel.find(1)
css_to_compile = Less::Parser.new.parse(css).to_css
rescue Less::Error => error
@my_model.errors[:base] << "Error message"
false
end
end
但false
並不妨礙交易得手,因此重定向發生。
您是否將您的MyModel對象保存在多個位置?如果沒有,您可以在成功執行'my_model.save'後調用'my_method',而不是使用回調。 – Gerry