myarray.to_xml
RuntimeError: Not all elements respond to to_xml
from /foo/vendor/rails/activerecord/lib/…/…/activesupport/lib/
active_support/core_ext/array/conversions.rb:62:in `to_xml’
from (irb):94
The standard thing to do is put classes in there instead of strings,
so each error would be an instance of class Error, which would respond
to to_xml with foo or whatever. See, for example, Pat
Maddox’s Blog:
If you are worried about reversibility, you can change active_support
\core_ext\array\conversions so that the to_xml method looks like this
at the top:
The XML you get back isn’t pretty, but it doesn’t crash:
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
foo
bar
Cleaning it up more than this might be a bit tricky. If this is
something a lot of people would like, I’d look at it some more, but I
think it’s pretty unusual, and it’s usually easier to use objects.
I’ve taken the easy (and hacky) way out by using an
ActiveRecord::Errors object which is transformed implements to_xml
quite nicely.
The hacky bit is that I’m not always adding an error that coincides
with an attribute of the model I’m exploiting … eg,
errors.add( :code, “#{code} is not found” )
…when my model object doesn’t actually have a “code” attribute.
Also… under some scenarios I may not have a model instance at all
but need to create one in order to gain access to the to_xml friendly
Errors object by doing something like…
errors = Player.new.errors
… which is of course hacky, but more readily thrown together than
implementing a custom errors class or modifying the conversions.rb
The Errors object is also nice because it allows multiple errors with
the same key…
errors.add( :code, “#{code} is not found” )
errors.add( :code, “#{code} has already been processed” )
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.