I have a resource defined in my routes.
resources :categories
And I have the following in my Category controller:
def show @category = Category.find(params[:id]) respond_to do |format| format.json { render :json => @category } format.xml { render :xml => @category } end end
The controller action works fine for json and xml. However I do NOT want the controller to respond to html format requests. How can I only allow json and xml? This should only happen in the show action.
What is the best way to achieve this? Also is there any good tips for DRYing up the respond_to block?
Thanks for your help.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With