Cannon Moyer
Cannon Moyer

Reputation: 3164

How to validate data that was altered in before_save

I have several validations that validate a Quote object. Upon validation, I have a before_save callback that calls an API and grabs more data, makes a few math computations and then saves the newly computed data in the database.

I don't want to trust the API response entirely so I need to validate the data I compute.

Please note that the API call in the before_save callback is dependent on the prior validations.

For example:

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. 

I need to be able to throw a validation error if possible with something like:

errors.add :base, "Tax didn't calculate correctly."

How can I validate values that were computed in my before_save callbacks?

Upvotes: 1

Views: 56

Answers (2)

PGill
PGill

Reputation: 3521

you can use 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

....

Upvotes: 1

Sebastian Estrada
Sebastian Estrada

Reputation: 307

Have you tried adding custom validation methods before save? I think this is a good approach to verify validation errors before calling save method

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

Then you should call it like

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

Upvotes: 0

Related Questions