首页 > 解决方案 > 如何验证在 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回调中计算的值?

标签: ruby-on-railsruby

解决方案


您可以使用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

....

推荐阅读