10

I want to respond with json to all formats.

I can force the render format to json so the action will render show.json despite the accept header:

  def show
    render formats: :json
  end

How I can set render format for all actions of the controller?

Something like this:

class GalleriesController < ApplicationController
  formats :json
end
freemanoid
  • 14,592
  • 6
  • 54
  • 77

3 Answers3

9

As a summary of all comments to the questions and readability for future users, you can do, as mentioned here:

before_filter :default_format_json

def default_format_json
  request.format = "json"
end
Community
  • 1
  • 1
Mick F
  • 7,312
  • 6
  • 51
  • 98
1

In your controller:

def my_action
  formats.clear
  formats << :json
end

(I've only tested this in Rails 4.2 and 3.2.)

formats returns an Array of format symbols. It is delegated to @_lookup_context, which is an instance of ActionView::LookupContext.

JellicleCat
  • 28,480
  • 24
  • 109
  • 162
-1

Overwrite the response content type. Read more about the response object here: http://guides.rubyonrails.org/action_controller_overview.html#the-response-object

before_filter :force_json

def force_json
  response.content_type = Mime[:json]
end

With respond_to:

def action
  respond_to do |format|
    format.any(:html, :js, :json) { render json: @object.to_json }
  end
end
phlegx
  • 2,618
  • 3
  • 35
  • 39