Rails 3 - Restricting formats for action in resource routes

Mike picture Mike · Feb 14, 2011 · Viewed 27.2k times · Source

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.

Answer

Mike picture Mike · Feb 15, 2011

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.