3

I'm trying to restrict a path in my routes file to a specific format.

i want this to work: app.com/party_favors/list.json

not this

app.com/party_favors/list or this app.com/party_favors/list.htmlor this app.com/party_favors/list.asdasdasda

is there a simple way to only allow a certain format in a match entry in the routes file?

Thanks!

skk5m
  • 31
  • 1
  • 2

5 Answers5

11

Rails 3 provides the :constraints option that can be specified on a route. This worked to route the same url to different controllers, depending on the format:

# http://app.com/party_favors.html gets routed to Web::PartyFavorsController#index
resources :party_favors, :module => "web", :constraints => {:format => :html}

# http://app.com/party_favors.xml gets routed to PartyFavorsController#index
resources :party_favors

I tried the :requirements option in Rails 2, but it doesn't seem to be as flexible. I'm not aware of any way to build it into the route for Rails 2, so you'd have to use one of the other suggestions.

Graeme
  • 970
  • 8
  • 16
  • this will not limit requests to those formats, see my answer below for the correct implementation – koonse Feb 06 '13 at 07:36
4

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

Community
  • 1
  • 1
koonse
  • 1,517
  • 1
  • 14
  • 16
3

You could explicitly map it like this

match 'party_favors/list.json', :controller => 'party_favors', :action => 'list', :format => 'json'
DanSingerman
  • 36,066
  • 13
  • 81
  • 92
  • thats what i thought i should be able to do but rake routes shoves a (.:format) on the end of the generated route :/ – skk5m Nov 17 '10 at 12:21
  • I think you will have to define all the paths and rely less on the generators –  May 16 '11 at 09:35
2

I found the following to work for me (Rails 3.1.1)

match '/categories/:id.json'=>'categories#show', :format=>false, :defaults=>{:format=>'json'}
arnie
  • 131
  • 1
  • 3
1

As far as i know you can handle this in controller rather than routes

 respond_to do |format|
  format.html
  format.json { render :json => @abcd }
  format.any { render :text => "Invalid format", :status => 403 }
end
Rakesh
  • 423
  • 1
  • 3
  • 17