Rails 3 - Restricting formats for action in resource routes Rails 3 - Restricting formats for action in resource routes ruby ruby

Rails 3 - Restricting formats for action in resource routes


I found that this seemed to work (thanks to @Pan for pointing me in the right direction):

resources :categories, :except => [:show]resources :categories, :only => [:show], :defaults => { :format => 'json' }

The above seems to force the router into serving a format-less request, to the show action, as json by default.


You must wrap those routes in a scope if you want to restrict them to a specific format (e.g. html or json). Constraints unfortunately don't work as expected in this case.

This is an example of such a block...

scope :format => true, :constraints => { :format => 'json' } do  get '/bar' => "bar#index_with_json"end

More information can be found here: https://github.com/rails/rails/issues/5548

This answer is copied from my previous answer here..

Rails Routes - Limiting the available formats for a resource


You could do the following in your routes.rb file to make sure that only the show action is constrained to json or xml:

resources :categories, :except => [:show]resources :categories, :only => [:show], :constraints => {:format => /(json|xml)/}

If this doesn't work you could try explicitly matching the action:

resources :categories, :except => [:show]match 'categories/:id.:format' => 'categories#show', :constraints => {:format => /(json|xml)/}