Search code examples
ruby-on-railsvalidationeventbrite

API Call after validation(ruby on rails)


I'm working on a ruby on rails app. The app is built on top of eventbrite and I'm using their api. After the "organizer" is saved in my database, I need to run an api call that creates the "organizer" in eventbrite. However, the issue that I'm running into is that I need this to run only if the model is validated. If the call to eventbrite fails for some reason(ie. the user exists) then the model should not save.

This is how I currently have it set up:

    #app/models/organizer.rb

    class Organizer < User


      after_commit :generate_eb_organizer_id

        def generate_eb_organizer_id
          e = EbWrapper.new({organizer: self})
          e.organizer_new
        end

      end

The model calls the "eventbrite wrapper", which is responsible for making the call to the api and handling any errors that come up. If there is an error, it will add an error to the @organizer instance.

    #app/models/eb_wrapper.rb

    class EbWrapper

      def initialize(args)
        @eb_client = EventbriteClient.new(Event.eb_auth_tokens)
        @organizer = args[:organizer]
      end

     def organizer_new

       begin 
        @eb_client.organizer_new(name: @organizer.eb_name, description:   @organizer.eb_description)
        rescue Exception => e
       @organizer.errors.add(" ", e.message)
     end

   end

end`

In short, the validation needs to include the call to event brite. However, if there is an issue(ie. the password is invalid) then the data on eventbrites servers should not be updated.

Does anybody have any ideas?

Thank you!


Solution

  • Try using after_save instead of after_commit.

    The situation you are describing needs to go through the entire process of saving a model in your database but should stop short if that same model encounters an error when being saved in the external system.

    This suggests that you need to go through all the actions of saving the model, such as the validations, but still need to be able to abort the database commit.

    Since after_commit happens after the database commit takes place it is impossible to abort the commit at that point. after_save, however, happens in-between validations and the database commit, so it is still possible to abort the commit (by returning false).

    ActiveRecord offers a rather staggering amount of callbacks that you can use. You might refer to this page, as it details several of them, and gives a good idea of the order in which they occur.