How can I do json rendering: in all actions of a Rails 4.2.1 controller

As per the response_with / reply_to note in the 4.2 ... Ruby Guides release notes and:

I would like to take this opportunity to split response_with / class-level reply_to into an external plugin. I'm not at all a fan of the code that comes out of using this pattern. It encourages the # to_json model, and it hides the difference between HTML and API responses in ways that overthrow code.

So how about we split this into a gem for 4.2 with the current behavior, but also the ability to get new behavior, as suggested here, via a config point. - DHH

I installed ActiveModelSerializer 0.9.3 and I found that it still works with:

render json: @object

in the controller ...

How can I render json:

default to the application controller?

+3


source to share


2 answers


You don't need to render any view directly from the application controller, but from the controller extending the ApplicationController. If you say response_with still works in your rails version, you just need to put response_to: json, like:

class MyController < ApplicationController
respond_to :json

def my_action
....
respond_with(@variable)
end
end

      



response_with will automatically render the view in the correct format based on the mime type of your request.

If it doesn't work, add the gem 'responseers', '~> 2.0' to your gem file.

+3


source


You can change your files routes.rb

to indicate the default format

routes.rb

resources :clients, defaults: {format: :json}

      



This will change the default response format for everything clients_controller

+2


source







All Articles