Unauthorised unless request.format.xml?


I'm using REST in my controller so therefore using respond to blocks but I'd like to return an unauthorised header for certain methods (create, update, delete) unless the request is for xml.

I don't want any actions to be performed unless the request format is xml.

So far I have tried:

  # POST /top_talkers   # POST /top_talkers.xml   def create     head :status => :unauthorized unless request.format.xml? ############ <============     @top_talker = TopTalker.new(params[:top_talker])

    respond_to do |format|       if @top_talker.save         format.xml { render :xml => @top_talker, :status => :created, :location => @top_talker }       else         format.xml { render :xml => @top_talker.errors, :status => :unprocessable_entity }       end     end   end

but that just gives a double render error.

Thanks, Toby

unless request.format.xml?   head :status => :unauthorized   render :nothing => true and return end

Should work. Vish

I've put that in a method called method_allowed? in application.rb and set it as a before_filter for the methods I want to restrict access to but when the before_filter is called I get a double render error. The respond to block still appears to execute.

Sorry that wasn't very clear.

I wan't to move the unless request.format... into a before_filter so I don't have to duplicate that unless..end in each method. How would I do a 'return' for the entire request rather than just the current method?

Thanks, Toby

Make sure you also return false from your filter to abort further processing.

Otherwise, your filter will run, *and* your action will run inducing another render, which isn't allowed.

Jeff softiesonrails.com essentialrails.com - New to Rails? Get up to speed in 2 days. Sept 21-22, 2007 in Chicago.