views:

119

answers:

2

Okay, I know you can override the to_xml method for a single instance of ActiveRecord object and it works just fine for me. But how would I go about overriding the to_xml method for collection of objects?

Suppose for Task model instance, I implemented to_xml which looks like this.

def to_xml
  super(:methods => [:tag_list], :include => {:project => {:include => {:folder => {}}}, :folder => {}})
end

Works just fine when a single task is to be serialized to xml. But when my code runs for collection of tasks, like in the following piece of code

render :xml => @tasks.to_xml

I get

wrong number of arguments (1 for 0)

/home/chirantan/.gem/ruby/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/array/conversions.rb:189:in `to_xml'
/home/chirantan/.gem/ruby/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/array/conversions.rb:189:in `to_xml'
/home/chirantan/.gem/ruby/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/array/conversions.rb:189:in `each'
/home/chirantan/.gem/ruby/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/array/conversions.rb:189:in `to_xml'
/var/lib/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `call'
/var/lib/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:134:in `_nested_structures'
/var/lib/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:58:in `method_missing'
/var/lib/gems/1.8/gems/builder-2.1.2/lib/builder/xmlbase.rb:31:in `tag!'
/~/blah/app/controllers/tasks_controller.rb:412:in `completed'

How do I make this work?

A: 

What happens if you just use:

render :xml => @tasks

Does the render method not automatically pick up your crafted to_xml?

Taryn East
Argh. I know that and that won't work :) This is a workaround. I want the collection of objects to be treated as an object to be serialize. If you take a look at the way `render :xml => @tasks` looks like and compare it with your solution, you will know.
Chirantan
+1  A: 

Your to_xml override should be declared

def to_xml options={}
   ....
end
Dean Radcliffe