Rails 4 - How to render JSON regardless of requested format?
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
You can use format.any
:
def action
respond_to do |format|
format.any { render json: your_json, content_type: 'application/json' }
end
end