我为ruby模型创建了一个自定义验证(使用luhn算法(。即使我只是从自定义验证中显式返回false
,对象仍然会保存。
这就是我的信用卡模型:
before_save :check_card_number
private
def check_card_number
return false unless card_number_luhn
end
def card_number_luhn
#luhn_algorithm_here_that_returns_true_or_false
end
但即使我只是返回false:
before_save :check_card_number
private
def check_card_number
return false
end
#so this is never even called
def card_number_luhn
#luhn_algorithm_here_that_returns_true_or_false
end
对象仍然保存。这是真的,即使我使用validate
而不是before_save
。发生了什么事?
从Rails 5,您需要显式调用throw(:abort)
# ...
before_save :check_card_number
# ...
def card_number_luhn
valid = #luhn_algorithm_here_that_returns_true_or_false
throw(:abort) unless valid
end
另一种方式:
ActiveSupport.halt_callback_chains_on_return_false = true
参考:https://www.bigbinary.com/blog/rails-5-does-not-halt-callback-chain-when-false-is-returned