Customizing to_xml and to_json in Rails
You probably already know (well, if you're a Rails developer) that you can use
To start, you can specify exactly which attributes to export with the
[sourcecode language='ruby']
@user.to_xml :only => [ :name, :phone ]
@user.to_xml :except => :password
@user.to_json :only => [ :name, :phone ]
@user.to_json :except => :password
[/sourcecode]
You can include associated records, nesting as needed, with the
[sourcecode language='ruby']
@user.to_xml :include => {:orders =>
{ :include => [:shipments, :backorders] }}
@user.to_json {:orders =>
{ :include => [:shipments, :backorders] }}
[/sourcecode]
[sourcecode language='ruby']
@user.to_xml :include => {:orders =>
{ :include => [:shipments, :backorders] },
:only => :order_date }
@user.to_json {:orders =>
{ :include => [:shipments, :backorders] },
:only => :order_date }
[/sourcecode]
You can create XML or JSON attributes from model methods by using the
[sourcecode language='ruby']
@user.to_xml :methods => :permalink
@user.to_json :methods => :permalink
[/sourcecode]
Additionally, there are some options that apply only to
to_xml
or to_json
to quickly get XML or JSON representations of Active Record model instances. But did you know that these methods are configurable? By default they simply dump all of the attributes of the model along with their values, but if you want to do something different, you can - and usually without overriding the base methods.To start, you can specify exactly which attributes to export with the
:only
or :except
options:[sourcecode language='ruby']
@user.to_xml :only => [ :name, :phone ]
@user.to_xml :except => :password
@user.to_json :only => [ :name, :phone ]
@user.to_json :except => :password
[/sourcecode]
You can include associated records, nesting as needed, with the
:include
option:[sourcecode language='ruby']
@user.to_xml :include => {:orders =>
{ :include => [:shipments, :backorders] }}
@user.to_json {:orders =>
{ :include => [:shipments, :backorders] }}
[/sourcecode]
:only
and :except
also work on includes:[sourcecode language='ruby']
@user.to_xml :include => {:orders =>
{ :include => [:shipments, :backorders] },
:only => :order_date }
@user.to_json {:orders =>
{ :include => [:shipments, :backorders] },
:only => :order_date }
[/sourcecode]
You can create XML or JSON attributes from model methods by using the
:methods
option:[sourcecode language='ruby']
@user.to_xml :methods => :permalink
@user.to_json :methods => :permalink
[/sourcecode]
Additionally, there are some options that apply only to
to_xml
. :skip_instruct
suppresses the XML processing instruction. :skip_types
suppresses the output of types to the XML. :dasherize => false
turns off dasherization of column names.