8

Can you make all routes default to json?

I have the following for an api scope but am wondering if you can do the same for the global scope?

  scope :api, defaults: {format: :json} do
    get "/search(/:query)(/:location)" => "search#index"
  end

For example all user resources would also default to json

resources :users
user2954587
  • 4,661
  • 6
  • 43
  • 101

2 Answers2

14

Use constraints

constraints format: :json do
  resources :users
end

or

resources :users, :defaults => { :format => 'json' }
Pavan
  • 33,316
  • 7
  • 50
  • 76
  • 1
    I accepted the answer and thought it worked but have created another question http://stackoverflow.com/questions/31421101/rails-routes-constraints-not-working-as-expected because it is not working as expected – user2954587 Jul 15 '15 at 13:53
4

According to Rails docs, in your config/routes.rb file:

defaults format: :json do
  resources :photos
end
Aleksandrus
  • 1,589
  • 2
  • 19
  • 31