Rails 4 - How to render JSON regardless of requested format?

Zach picture Zach · May 30, 2014 · Viewed 14.5k times · Source

I'd like a Rails controller (all of them, actually, it's an API) to render JSON always always.

I don't want Rails to return "route not found", or try and fail to find an HTML template, or return 406. I just want it to automatically and always render JSON, e.g. from a RABL or JBuilder view.

Is this possible? Related questions seem to have answers that have the aforementioned downsides.

Answer

vee picture vee · May 30, 2014

You can add a before_filter in your controller to set the request format to json:

# app/controllers/foos_controller.rb

before_action :set_default_response_format

protected

def set_default_response_format
  request.format = :json
end

This will set all response format to json. If you want to allow other formats, you could check for the presence of format parameter when setting request.format, for e.g:

def set_default_response_format
  request.format = :json unless params[:format]
end