繁体   English   中英

如何验证在 before_save 中更改的数据

[英]How to validate data that was altered in 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

....

您是否尝试在保存之前添加自定义验证方法? 我认为这是在调用 save 方法之前验证验证错误的好方法

class Quote < ActiveRecord::Base
  validate :api_and_compute_tax

  private

  def api_and_compute_tax
    # ...API call and result parse
    if api_with_wrong_response?
      errors.add :base, "Tax didn't calculate correctly."
    end
  end
end

那么你应该这样称呼它

quote.save if quote.valid? # this will execute your custom validation

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM