Rails to_xml, thar be dragons.

Ok, so I have been using to_xml to handle generating xml serialised lists for a restful xml interface.

I came across this interesting situation.

If you are serialising a collection which is implemented as a set of subclasses using STI, the to_xml will generate different xml depending on which class of items it sees first.

For instance, if you start the list with an instance of the base class, it will generate a list encapsulated with the plural name of the class name, and each element will be a singular of the class name for the base class, irrespective of which classes each of the objects are.

BUT, if the first item in the list is one of the subclasses, the to_xml call will see that it is a heterogenious list (presumably because the successive items don’t all return ‘true’ for .kind_of? of the class of the first item, and will generate a xml list encapsulated as <record> entities within a <records> list.

Oh, that makes me SOO happy.

Leave a Reply

Your email address will not be published. Required fields are marked *