4

A usual usage of respond_to is like

respond_to do |format|
  format.html
  format.xml { render :xml => @data }
end

can it be made so that when the format is not supported (such as json or csv not being supported above), instead of returning nothing, return a text line saying "the format is not supported", or better yet, have it automatically report "only html and xml is supported"? It can know only html and xml are supported by the existing format.html and format.xml lines there. (if possible)

nonopolarity
  • 146,324
  • 131
  • 460
  • 740
  • [rails-respond_to-return-unknown-format-error](https://cbabhusal.wordpress.com/2014/10/07/rails-respond_to-return-unknown-format-error/) – Shiva May 12 '16 at 03:13

2 Answers2

7

You should be able to use format.all

respond_to do |format|
  format.html
  format.xml { render :xml => @data }
  format.all { render :text=>'the format is not supported' }
end

If you want to list the supported formats you'll need to extend the Responder class.

Put this in something like config/initializers/extend_responder.rb

module ActionController
  module MimeResponds
    class Responder

      def valid_formats
        @order.map(&:to_sym)
      end

    end
  end
end

Then use this in your controller:

respond_to do |format|
  format.html
  format.json { render :text=>'{}' }
  format.all { render :text=>"only #{(format.valid_formats - [:all]).to_sentence} are supported" }
end
aNoble
  • 7,033
  • 2
  • 37
  • 33
0

I found I was still getting missing template errors with the solution trying to render text, so I went with this approach:

  respond_to do |format|
    format.html 
    format.all { head :not_found }
  end
TerryS
  • 7,169
  • 1
  • 17
  • 13