Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit the resource formats in the Rails routes file

When routing resources in Rails the optional format attribute is automatically appended to the generated routes. This is so that the resource in question can be requested as either XML, HTML etc. Which formats that is actually allowed is usually described in the controller using respond_to.

But in many cases you only want to support HTML and it feels like an overhead to write respond_to :html in every action in every controller. It would therefore be cool if there where a way to limit to allowed content types already when building the routes in the routes.rb file, e.g.

map.resources :users, :formats => :html
map.resources :users, :formats => [:html, :xml]
map.resources :users, :formats => {:index => :html, :show => [:html, :xml]}

Is there a way to achieve this either native or via a plugin?

P.S. The usual way to work around this is to just ignore the problem and don't use respond_to in the actions. But this actually doesn't limit the allowed content types. Instead it just expects that a template exists in the views directory for each possible content type. If one doesn't exist when requested, the system will throw a HTTP 500 error.

like image 505
Thomas Watson Avatar asked Sep 03 '09 16:09

Thomas Watson


1 Answers

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

like image 97
koonse Avatar answered Sep 30 '22 23:09

koonse