Hugo Carlos Hugo Carlos - 2 years ago 70
JSON Question

How to respond to an external API callback in Rails 4 without it looking for a template?

I have a Rails 4 app that talks to an external payment gateway that, after processing the payment (not as the response to my request, but with a POST to an endpoint in my app).

This endpoint has a controller that only deals with json but everytime the external API hits the endpoint I get errors in the server log saying that it couldn't find the template for the action, although everything else works fine and the app process the json body correctly.

This is my route:

match 'callback', to: 'gateway#callback', via: [:post], as: :gateway_callback

This is my controller (abbreviated):

class GatewayController < ApplicationController

respond_to :json

def callback
if params && params[:event]
case params[:event]
when ... (several cases identical to this one)

render json: { status: 200 }
render json: { status: 406 }

The response correctly renders

"status": 200

And the
does what it has to do. But my server screams:

ActionView::MissingTemplate (Missing template gateway/callback, application/callback with {:locale=>[:"pt-BR", :pt], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builde
r, :raw, :ruby, :coffee, :haml, :jbuilder]}

How do I tell Rails that I only want to sent a json response without any template whatsoever?

Answer Source

You can set the default from the route itself. Just set the defaults.format attribute to :json:

match 'callback', to: 'gateway#callback', via: [:post], as: :gateway_callback,
                  defaults: { format: :json }     # <- Added line of code
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download