In rails, how can I incorporate external api calls tied to model create/update that do not trigger upon db:seed?

StackOverflow https://stackoverflow.com/questions/18789165

  •  28-06-2022
  •  | 
  •  

Question

When an activerecord for a "category" gets created in my rails app, I need to send the data immediately to an external system via a rest api. Currently I have the rest client api call in the after_commit callback of my "category" model.

Is this the best practice in general or is there a better pattern to use?

If so, how do I prevent the api call from executing each time I seed the database for my specs?

class Category < ActiveRecord::Base

    attr_accessible ............

    ....more stuff....

    after_commit :api_post, on: :create

    def api_post

        ms = RestClient.new()

        ms.post :category, self.to_json(:root => true)

    end

end
Was it helpful?

Solution

Don't send it unless you're in production:

def api_post

    if Rails.env.production?
        ms = RestClient.new()
        ms.post :category, self.to_json(:root => true)
    end

end

This will skip it for development and test environments. The if check can be moved around as desired (perhaps to be around the after_commit instead, if it suits).

OTHER TIPS

My first thought is that you should probably do those api calls in controllers rather than in models, since it's request related (and controllers are all about handling requests, after all). But this does not answer your question.

I assume you want to use that seeding in production, else @Nick answer is correct.

You could pass an environment variable when running the seed task :

SEEDING=true rake db:seed

Then, you can use it in your model :

def api_post
  unless ENV[ 'SEEDING' ].present?
    ms = RestClient.new()
    ms.post :category, self.to_json(:root => true)
  end
end

Certainly not the most elegant thing, though ...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top