views:

16

answers:

1

Consider the following scenario:

You have an account model You have an external service which manages subscriptions (such as CheddarGetter).

You do not want to create a customer on CG unless the data entered passed your own validations, and likewise you don't want to save the customer down to your own database unless CG accepts the customer record and payment details.

However, you want any validation errors from either side to be made available to the user.

So, how would you go about this? Validating either side is simple, but getting both sides working together seems difficult.

A: 

I have found a way of achieving this.

Local validations are carried out as normal. External validations are carried out in a before_create callback:

  def save_customer_on_cheddargetter
    begin
      external_api_stuff
    rescue => error
      errors.add :base, error.message
      return false
    end
    true
  end

As long as the callback returns false for an invalid record, and adds errors to base, the user sees one validation, and also blocks saves to the database should the API return an invalid record.

Neil Middleton