Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render JSON instead of HTML as default?

I try to tell rails 3.2 that it should render JSON by default, and kick HTML completely like this:

respond_to :json      def index   @clients = Client.all   respond_with @clients end 

With this syntax, I have to add .json to the URL. How can I achieve it?

like image 621
trnc Avatar asked May 21 '12 08:05

trnc


People also ask

How to render JSON as HTML?

Just call the library in whatever way/tech you are using and then append the result of the JSON data passed on to renderjson() function. It takes in the JSON you want to render as a single argument and returns an HTML element.

What is rendering in JSON?

render :json essentially calls to_json and returns the result to the browser with the correct headers. This is useful for AJAX calls in JavaScript where you want to return JavaScript objects to use. Additionally, you can use the callback option to specify the name of the callback you would like to call via JSONP.


2 Answers

You can modify your routes.rb files to specify the default format

routes.rb

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

This will modify the default response format for your entire clients_controller

like image 113
rogeliog Avatar answered Sep 28 '22 03:09

rogeliog


This pattern works well if you want to use the same controller actions for both. Make a web version as usual, using :html as the default format. Then, tuck the api under a path and set :json as the default there.

Rails.application.routes.draw do    resources :products    scope "/api", defaults: {format: :json} do     resources :products   end  end 
like image 33
Mark Swardstrom Avatar answered Sep 28 '22 03:09

Mark Swardstrom