我使用的是Rails 5的关联回调。我在文档中读到,如果你想中止从关联中删除对象,你必须抛出一个异常:
如果before_add回调引发异常,则不会将对象添加到集合中。类似地,如果before_remove回调引发异常,则不会从集合中移除该对象。
我正是这么做的,但服务器崩溃了,出现了:
UncaughtThrowError (uncaught throw :abort)
我的代码是这样的:
def can_remove_association(object)
return unless object.condition
errors[:base] << "Can't be removed."
throw(:abort)
end
知道发生了什么事吗?throw(:abort)
正在避开要删除的对象,但我得到了一个丑陋的500!
一些参考:http://blog.bigbinary.com/2016/02/13/rails-5-does-not-halt-callback-chain-when-false-is-returned.html
是的,您需要使用
raise('abort')
请参阅https://ruby-doc.org/core-2.4.0/Kernel.html#method-i路
以及https://ruby-doc.org/core-2.4.0/Kernel.html#method-i-raise