开发者

to_xml with :only and :methods

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 whe开发者_JS百科n 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)


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜