Using ActiveRecord's to_xml to produce custom xml including deep level associations

ActiveRecord provides a powerful method to all its records called to_xml. Most web developers using RoR should be familiar with its usage and hopefully use it for their simple xml production needs. But what do you do when you need to produce xml that is selective, includes associations, or contains custom tags? There are many ways to manipulate to_xml's output and I'll explain a few below.

The Options Hash

The most obvious way to change the output is to use the options hash outlined in the docs. A short list of options you might want to explore is:

  • except => [:attr1, :attr2] -- excludes attributes in array from output
  • only => [:attr1, :attr2] -- output contains only the specified attributes
  • include => [:assoc1, :assoc2] -- calls to_xml on the given first level association and nests it in the output
  • methods => [:meth1, :meth2] -- adds a tag to output in the format \[method output]\

Usage is incredibly simple:

# grab xml for a record and its child
  my_record.to_xml(:include => :child)

  # same, but only output the ids and names (assuming both have these attributes)
  my_record.to_xml(:only => [:id, :name], :include => :child)

Behold, the Builder

A fantastic feature of to_xml that Ryan blogged about last year is that it yields the builder, thus allowing you to add arbitrary tags into the output. What's more is you can pass the builder into another object's to_xml method inside the outer block and produced nested xml.

For example:

# Arbitrarily insert a tag
  my_record.to_xml do |xml|
    xml.some_tag some_value #=> <some_tag>some_value</some_tag>

  # I want to get xml for my record and all its children
  my_record.to_xml do |xml|
    my_record.children.each{|child| child.to_xml(:builder => xml, :skip_instruct => true)}

You can nest as deep as you want without overriding a model's own to_xml method:

output = my_record.to_xml do |xml|  
    my_record.children.each do |child|
      child.to_xml(:builder => xml, :skip_instruct => true) do |fxml|
        child.grandchild.to_xml(:builder => fxml, :skip_instruct => true)

deep_xml: Model methods that utilize (but do not overwrite) to_xml

I chose to write methods in the models that handled including the children's xml such that a single call to my_record.full_xml would produce nested xml automatically. Notice how the builder is being passed to the children, it's important!

class ParentClass < ActiveRecord::Base  
    has_many :children

    def deep_xml(builder=nil)
      to_xml(:builder => builder) do |xml|
        children.each{|child| child.deep_xml(xml)}

  class Child < ActiveRecord::Base
    belongs_to :parent
    has_one :grandchild

    def deep_xml(builder=nil)
      to_xml(:builder => builder, :skip_instruct => true) do |xml|
        grandchild.to_xml(:builder => xml, :skip_instruct => true)

  class Grandchild < ActiveRecord::Base
    belongs_to :child

# Now the call is simple:
Parent.firstdeep_xml #=> custom xml for a parent that includes its  
                        # children and their grandchildren (1 each in this case)

There's not much to it, but I found this solution to be nice shorthand that cleaned up ugly nested to_xml blocks I was writing over and over. I call my_record.deep_xml from any layer of the family tree and return a nice drill down of data to the leaf children. It's great if you're working with a complicated database and need to be able to present your data in xml.

If you are so inclined...

If you really need to, you can just overwrite the to_xml method in the model. While fine to do if you know you'll always want that one specific template, I avoid it as much as possible and won't cover it since examples are all over the blogosphere. Why not just make a separate function to avoid producing unexpected results for someone else who joins your project later on?

comments powered by Disqus