[ACCEPTED]-Rails 4 - How to render JSON regardless of requested format?-rabl

Accepted answer
Score: 48

You can add a before_filter in your controller to set 4 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 3 response format to json. If you want to allow 2 other formats, you could check for the presence 1 of format parameter when setting request.format, for e.g:

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

You can use format.any:

def action
  respond_to do |format|
    format.any { render json: your_json, content_type: 'application/json' }
  end
end

0

Score: 5

It's just:

render formats: :json

0

Score: 0

I had similar issue but with '.js' extension. To 1 solve I did the following in the view: <%= params.except!(:format) %> <%= will_paginate @posts %>

Score: 0

I tried the above solutions and it didn't 11 solve my use case. In some of the controllers 10 of my Rails 4.2 app, there was no explicit 9 render called. For example, a service object was 8 called and nothing was returned. Since they 7 are json api controllers, rails was complaining 6 with a missing template error. To resolve 5 I added this to our base controller.

  def render(*args)
    options = args.first
    options.present? ? super : super(json: {}, status: :ok)
  end

It's 4 a large app I'm converting to Rails 5, so 3 this is just a safety measure as I removed 2 the RocketPants gem that seemed to do this automatically.

As 1 a note, my controllers inherit from ActionController::Base

More Related questions