Tuesday, August 01, 2006

RubyOnRails howto: Create a simple XML view of a persisted object

I like to share with you a simple and easy way to generate an XML output for a persisted object using a layout templete. I’ve found a similar implementation surfing the RubyOnRails site and it works too.
Supose you have a “documents” repository in your relational database and these documents have 3 fields: title, author and a description. What we want to do is to (generate) and show a XML file for every listed object.
So, First you have to add a new file in your application view folder describing your xml desired structure, this file act as the XML templete, I will name it esml.rxml:

xml.instruct! :xml, :version=>"1.0"
xml.instruct! :rss, :version=>"2.0"
xml.document {
xml.title("a",@document.title)
xml.author(@document.author.name)
xml.description(@document.body)
}


Next add a link to your XML document in your default “list” or “show” page (in the View folder of course):

link_to 'XML view of the document', :action => 'esml', :id => document

Then you have to create the action in your application controller .rb file (I have named it “esml”, I know! , I’m not very original…)

def esml
@document = Document.find(params[:id])
render :layout => false
end


Youre done!, that’s all you need to do , now click through the new link, you will find a fresh XML document for every document requested!...yep, is too easy, isn’t it?

2 comments:

Anonymous said...
This comment has been removed by a blog administrator.
Anonymous said...
This comment has been removed by a blog administrator.