You probably already know (well, if you’re a Rails developer) that you can use 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:


@user.to_xml :only => [ :name, :phone ]
@user.to_xml :except => :password
@user.to_json :only => [ :name, :phone ]
@user.to_json :except => :password 

You can include associated records, nesting as needed, with the :include option:


@user.to_xml :include => {:orders =>
  { :include => [:shipments, :backorders] }}
 @user.to_json {:orders =>
  { :include => [:shipments, :backorders] }}

:only and :except also work on includes:


@user.to_xml :include => {:orders =>
  { :include => [:shipments, :backorders] },
  :only => :order_date }
@user.to_json {:orders =>
  { :include => [:shipments, :backorders] },
  :only => :order_date }

You can create XML or JSON attributes from model methods by using the :methods option:


@user.to_xml :methods => :permalink
@user.to_json :methods => :permalink 

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.