STI and to_xml

As I mentioned in the explanation for my response_from plugin, I have two apps that communicate via a private XML REST API. This is trivial using my xml_response_from method (in my response_from plugin) and with Rail's to_xml; trivial, that is, unless you want to use single table inheritance.

For example, let's say you have:

 class User < ActiveRecord::Base
 end
 class Typical < User
 end
 class Admin < User
 end
 class AccountController < ApplicationController
   def list
    @users = User.find_all
    responds_to do |wants|
     wants.html
     wants.xml { render :xml => @users.to_xml }
    end
   end
 end

The @users.to_xml will produce something like:

 <records>
   <record>
    <name>Joe Schmoe</name>
    <password>db9c93f05d2e418c18</password>
    <email>joe@example.com</email>
    <id type="integer">1</id>
   </record>
 </records>

This totally leaves out the STI information: not only is the type field is not included in the <record> element, but the element should be called something better than just <record>.

The quick solution I used is:

 xml = '<users>' +
   @users.map.{ |m| m.to_xml :skip_instruct => true }.join('\n')  +
   '</users>'
 render :xml => xml

Does anyone have a better idea? Perhaps a patch for to_xml?

Advertisements

2 Comments

  1. Justin
    Posted September 1, 2008 at 5:27 pm | Permalink

    Did you ever figure out a workaround to have to_xml return the type?

  2. Posted September 1, 2008 at 8:42 pm | Permalink

    Never did, sorry.


%d bloggers like this: