Force format for all actions

I want to answer json in all formats.

I can force the json rendering format so that the action displays show.json despite the accept header:

  def show render formats: :json end 

How to set up a rendering format for all controller actions?

Something like that:

 class GalleriesController < ApplicationController formats :json end 
+6
source share
2 answers

As a summary of all comments on 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 
+5
source

Overwrite the content type of the response. 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 response_to:

 def action respond_to do |format| format.any(:html, :js, :json) { render json: @object.to_json } end end 
-1
source

Source: https://habr.com/ru/post/957571/


All Articles