Jump to content

The ultimate community for Ruby on Rails developers.


External Web Service Call - Belong in Controller or Model?

api webservice model controller

  • Please log in to reply
1 reply to this topic

#1 jmesserer



  • Members
  • 4 posts
  • LocationMinneapolis, MN

Posted 19 September 2013 - 10:51 PM

While watching Railscasts #366 Sidekiq I was left wondering why the call to the external web service was made from the controller rather than the model ... can anyone shed some light on this or explain the specific logic behind leaving it in the controller vs. the model?


I tend to follow fat modal / skinny controller and the web service call seems to be business logic and should go into the model. I would put it into an 'after_create' callback on the model (see below). Is my understanding/logic where this belongs wrong?


I know this wasn't the focus of this specific Railscast but even after he abstracted the web service call into a Sidekiq job the Sidekiq call is left in the controller.

# app/controllers/snippets_controller.rb
def create
    @snippet = Snippet.new(params[:snippet])
    if @snippet.save
        # uri = URI.parse("http://pygments.appspot.com/")
        # request = Net::HTTP.post_form(uri, lang: @snippet.language, code: @snippet.plain_code)
        # @snippet.update_attribute(:highlighted_code, request.body)
        #            OR
        redirect_to @snippet
        render :new
# app/models/snippet.rb
class Snippet < ActiveRecord::Base
    after_create {|record| PygmentsWorker.perform_async(record.id)}

Thanks =~ J

#2 stevieing



  • Members
  • 40 posts

Posted 20 September 2013 - 08:19 AM

In my personal opinion a call to an external web service is a request and so should be in the controller.


In the end it is up to you but if you are interacting with external services, models etc. then you may find your code more difficult to maintain.



  • james likes this

Also tagged with one or more of these keywords: api, webservice, model, controller

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users