ruby-on-rails - 自定义 Ruby/rails 模型验证不起作用
问题描述
我为 ruby 模型创建了一个自定义验证(使用 luhn 算法)。即使我明确地false
从自定义验证中返回,对象仍然保存。
这就是我的 CreditCard 模型中的内容:
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
推荐阅读
- python - 无法使用 ctype 在 python 中加载 .dll
- php - 从 OneToMany 类别实体上的 Doctrine 数据库结果生成多维数组的递归函数
- python - 不再满足条件时调用具有 lock.aquire() 的函数
- android - 删除 TextInput 下划线 React-Native
- google-sheets - 按降序使用 SORT() 时排除空单元格
- azure-functions - Azure 持久功能扩展
- c - Gtk 在按钮单击时显示和隐藏容器
- asp.net-mvc-5 - 上传图片的挑战。其他信息正在提交到数据库,但图像未上传
- vba - 将数组添加到集合
- swift - 如何避免 Mojave 上的 Safari 扩展程序崩溃?