Search code examples
ruby-on-railsrespond-torespond-with

set a rails controller's response type to xml


i'm quite new to rails. i'm trying to set a rails controller's response type to xml, but not having much luck. i could certainly afford to better understand how respond_to and respond_with work.

here's what my controller looks like:

class ResponsesController < ApplicationController

 respond_to :xml

  def index

    require 'rubygems'   
    require 'telapi'

        ix = Telapi::InboundXml.new do

          Say('Hello.', :loop => 3, :voice => 'man')
          Say('Hello, my name is Jane.', :voice => 'woman')
          Say('Now I will not stop talking.', :loop => 0)
        end

        respond_with do |format|
            format.xml { render }
        end

        puts ix.response 

    end
end

this leads to an http retrieval failure. can someone advise me how to how i can fix the controller and set its response type to xml? also, a cogent 1-2 liner of how respond_to and respond_with work would be awesome!

thanks everyone.


Solution

  • replace

      respond_with do |format|
                format.xml { render }
            end
    

    with

    respond_with(ix)
    

    There are 2 ways of rendering a xml. Example 1 uses respond_to that means "every single method will use xml and use the object parse in from respond_with"

    Example 2 uses respond_to that means "use the block below to declare what type of respond and the object to be parse"

    example 1:

    class ResponsesController
      respond_to :xml #respond_to A
    
      def index
        respond_with(@asd) # respond_with A
      end
    end
    

    example 2:

    def ResponsesController
    
      def index
        respond_to do |format|
         format.xml { render xml: @asd}
        end
      end
    end
    

    http://blog.plataformatec.com.br/2009/08/embracing-rest-with-mind-body-and-soul/