Amanda
Amanda

Reputation: 9

Ruby on Rails XML

I'm looking to create a Rails application which generates XML instead of HTML. How do I do this?

Upvotes: 0

Views: 1441

Answers (4)

edebill
edebill

Reputation: 7715

You have three options.

Option 1 is to explicitly render auto-generated XML.

render :xml => @object

which will call @object.to_xml for you. You can tweak the output with options:

render :xml => @object.to_xml(:except => [:private1, :private2], :include => [:associated_class])

This is very quick and easy. It will work pretty well if you don't need tight control of the output. The XML representation is being controlled in the controller instead of the view, which is somewhat messy, but not too bad as long as you're not getting fancy.

Option 2 is to create templates named .xml.erb instead of the normal .html.erb. These are just XML files with normal ERB markup in them. If the request comes in for an URL with .xml on the end of it, the default behaviour (using normal scaffolding in the controller) is to display those templates instead of the HTML ones). Frequently scaffolds have a block like:

respond_to do |format|
  format.html # show.html.erb
  format.xml { render :xml => @object.to_xml }
end

In this case (assuming you want to allow HTML as well) you'd want to remove the {} block on the format.xml line so it falls back to the default template.

Option 3 is to write your own object -> XML mapping, using something like Builder (which is very very slick and is included with Rails). Suddenly your model is worrying about its views.

I'd suggest doing option 1 until you start running into trouble (sometimes a seemingly benign change will cause the XML output to change - perhaps reordering tags) and then switch to option 2. Having those XML files there makes it very very clear exactly what's being displayed, much like having HTML view files. Option 3 works, but you're mixing logic (the rest of your model) with presentation.

Upvotes: 5

Veeti
Veeti

Reputation: 5300

You can either use the Builder library for Ruby, or use ActiveRecord's XML serialization functionality.

Upvotes: 2

Sheldon
Sheldon

Reputation: 2628

Here you have:

http://www.xml.com/pub/a/2007/01/17/making-xml-in-a-rails-app-xml-builder.html

Hope it serves!

Upvotes: 1

Azeem.Butt
Azeem.Butt

Reputation: 5861

You write XML instead of HTML. Rails doesn't particularly care what it serves.

Upvotes: -2

Related Questions