0

I'm calling to_xml on an ActiveRecord object with both :only and :methods parameters.

The method that I'm including returns a collection for AR objects. This works fine without the :only param, but when that is added I just get the default to_s representation of my objects.

i.e

<author><books>#&lt;Book:0x107753228&gt;</books>\n</author>

Any ideas?

Update, here is the code:

class Author < ActiveRecord::Base
  def books
    #this is a named scope
    products.by_type(:book)
  end
end

Author.to_xml(:methods => :books, :only => :id)
mu is too short
  • 426,620
  • 70
  • 833
  • 800
Jake
  • 39
  • 1
  • 4

2 Answers2

2

AFAIK, you have to handle the child objects by hand:

a = Author.find_by_whatever
xml_string = a.to_xml(:only => :id) { |xml|
     a.books.to_xml(:builder => xml, :skip_instruct => true)
}

The :skip_instruct flag tells the builder to leave out the usual <?xml version="1.0" encoding="UTF-8"?> XML preamble on the inner blob of XML.

The XML serializer won't call to_xml recursively, it just assumes that everything from :methods is simple scalar data that should be slopped into the XML raw.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
0

Off the top of my head, I think you can do:

Author.to_xml(:methods => {:books => {:only => :id}})

I've used something similar when including AR associations into the XML, not so sure about custom methods though.

jemminger
  • 5,133
  • 4
  • 26
  • 47