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_xml
method Rails adds toActiveRecord
,Array
, andHash
uses thebuilder
gem by default. The XML is also passed throughActiveSupport::XmlMini
where the addition of thenil="true"
attribute is hard coded to always be added fornil
attributes.You should probably look at using
builder
directly to build your XML if these values are problematic.You could also use other XML libraries. I only recommend
builder
because it is the rails default and likely already installed.Another option is to convert the object into a
Hash
first (object.attributes
works ifobject
is anActiveRecord
instance). You can then convert any nils into blank strings.