I need your help on to_xml function. How can i make all nil="True" value to a default value '' (blank) when exporting to xml from active record.
Ruby on Rails to_xml nil="True"
1.2k views Asked by Ben At
2
There are 2 answers
0
On
You can add a method to set special default values for XML generation. This method can then be called from an overridden to_xml method which duplicates the record in memory, sets default values and finally generates the xml. Example code:
class Post < ActiveRecord::Base
def set_xml_defaults
blanks = self.attributes.find_all{|k,v| v.nil? }.map{|k,v| [k,''] }
self.attributes = Hash[blanks]
end
alias_method :to_xml_no_defaults, :to_xml
def to_xml(options = {}, &block)
dup = self.dup
dup.set_xml_defaults
dup.to_xml_no_defaults
end
end
The
#to_xmlmethod Rails adds toActiveRecord,Array, andHashuses thebuildergem by default. The XML is also passed throughActiveSupport::XmlMiniwhere the addition of thenil="true"attribute is hard coded to always be added fornilattributes.You should probably look at using
builderdirectly to build your XML if these values are problematic.You could also use other XML libraries. I only recommend
builderbecause it is the rails default and likely already installed.Another option is to convert the object into a
Hashfirst (object.attributesworks ifobjectis anActiveRecordinstance). You can then convert any nils into blank strings.