trnc
trnc

Reputation: 21577

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?

Upvotes: 48

Views: 30260

Answers (4)

Cristiano Mendonça
Cristiano Mendonça

Reputation: 1282

Extending Mark Swardstrom's answer, if your rails app is an API that always returns JSON responses, you could simply do

Rails.application.routes.draw do
  scope '/', defaults: { format: :json } do
    resources :products
  end
end

Upvotes: 1

Mark Swardstrom
Mark Swardstrom

Reputation: 18070

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

Upvotes: 16

jdoe
jdoe

Reputation: 15771

If you don't need RESTful responding in your index action then simply render your xml response directly:

def index
  render json: Client.all
end

Upvotes: 11

rogeliog
rogeliog

Reputation: 3692

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

Upvotes: 92

Related Questions