Search code examples
ruby-on-railsruby-on-rails-3activeresourceactioncontroller

How do I make my app respond to a format based on a querystring parameter?


For example, I would like

/apples/123?_format=json

to act like

/apples/123.json

where it renders the *.json.* templates, executes respond_to {|format| format.json {...}}, etc.

Is this at all possible?

Thanks!


Solution

  • You can do the following to disable Rails' automatic handling of the .ext format:

    constraints format: false do
      resources :apples
      # ...
    end
    

    Then, and this is a bit gross but I don't see a better way to do this at the moment, you can do the following to update ActionController on what format to serve:

    class ApplicationController < ActionController::Base
      before_filter :set_format_from_query_string
    
    private
    
      def set_format_from_query_string
        request.format = params.fetch(:_format, 'json')
      end
    end
    

    This will allow your respond_to block to toggle based on the _format query string parameter and uses json as the default format.