Rails 3 Routes and Format Specification

I am trying to limit the path in the routes file to a specific format.

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

not this one

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

Is there an easy way to allow only a specific format in a mapping entry in a routes file?

Thank!

+3
source share
6 answers

Rails 3 provides a parameter :constraintsthat 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

:requirements Rails 2, . , Rails 2, .

+11

, (, html json). , .

...

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

: https://github.com/rails/rails/issues/5548

.

Rails Routes -

+4

:

match 'party_favors/list.json', :controller => 'party_favors', :action => 'list', :format => 'json'
+3

I found a job for me (Rails 3.1.1)

match '/categories/:id.json'=>'categories#show', :format=>false, :defaults=>{:format=>'json'}
+2
source

As far as I know, you can handle this in the controller, not in routes

 respond_to do |format|
  format.html
  format.json { render :json => @abcd }
  format.any { render :text => "Invalid format", :status => 403 }
end
+1
source

I ended up working with this solution for my 2 open public methods. in front of the filter as it gives out 404s. I really want a cleaner way to do this, though.

Thank you all for your answers. I appreciate it.:)

0
source

Source: https://habr.com/ru/post/1775406/


All Articles