ruby-on-rails - 如何验证在 before_save 中更改的数据
问题描述
我有几个验证Quote
对象的验证。验证后,我有一个before_save
回调,它调用 API 并获取更多数据,进行一些数学计算,然后将新计算的数据保存在数据库中。
我不想完全信任 API 响应,所以我需要验证我计算的数据。
请注意,before_save
回调中的 API 调用取决于之前的验证。
例如:
validates :subtotal, numericality: { greater_than_or_equal_to: 0 }
before_save :call_api_and_compute_tax
before_save :compute_grand_total
#I want to validate the tax and grand total numbers here to make sure something strange wasn't returned from the API.
如果可能的话,我需要能够抛出验证错误,例如:
errors.add :base, "Tax didn't calculate correctly."
如何验证在我的before_save
回调中计算的值?
解决方案
您可以使用after_validation
after_validation :call_api_and_compute_tax, :compute_grand_total
def call_api_and_compute_tax
return false if self.errors.any?
if ... # not true
errors.add :base, "Tax didn't calculate correctly."
end
end
....
推荐阅读
- php - 在 PHP 中调用 ajax 函数时如何获取页面 URL?
- html - 打印预览(表格)上不显示边框
- unix - 根据起始字母过滤掉单词
- vue.js - 我将如何为可嵌入的 Vue 应用程序优化 SEO?
- laravel - 与 Laravel Jetstream 一起使用时,未编译 Tailwind 颜色
- firebase - 如何从卡上的 Firebase 检索数据并将数据提取到详细信息屏幕?
- docker - 如何要求用户登录才能推送到 docker 注册表?
- javascript - Fetch 返回 null 但页面刷新后返回对象。如何解决?
- javascript - 如何获取数组值并将其设置在我的内部 html 中?
- python - 以管理员身份启动后 Python 程序未运行