Thursday, February 18, 2010

Rendering XML with Rails

I had to code a webservice with Rails yesterday. Its obvious purpose was to respond with XML formatted data to an HTTP GET request. I looked at some of the examples out there and ran into trouble. I lost some time searching for a solution, so here's the summary of the solution to save others the hassle.

Here's what people recommend doing to render XML from a HTTP request in Rails:


class WebServiceController < ApplicationController

def people
@people = Person.find :all
respond do |format|
format.xml
end
end

end



And the corresponding people.xml.builder in /views/web_service/:


xml.instruct! :xml, :version=>"1.0"

xml.people do
@people.each do |person|
xml.person do
xml.firstname person.first_name
xml.lastname person.last_name
xml.age person.age
end
end
end



When testing this, I kept getting browser errors about invalid XML. When I looked at the data that was returned from my webservice call, I realised that the XML was generated like I wanted, but it was subsequently embedded into the application layout I am using for all of the views (views/layouts/application.rhtml).

The issue was resolved by changing my controller code to


class WebServiceController < ApplicationController

def people
@people = Person.find :all
render :template => 'web_service/people.xml.builder', :layout => false
end

end

5 comments:

Unknown said...

Most excellent this was just what I was looking for.

Tankyou for writing up this very helpful guide.

Nige

Anil said...

Thanks man. Worked in first attempt.

Pravin Mishra said...

tks, helped me a lot..!!!!!!

Javier de Vega Ruiz said...

Another way:

def show
@model = Model.find params[:id]
render :xml => @model
end

Anonymous said...

nice! worked!