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.


5 comments
Comments feed for this article
November 7, 2008 at 7:59 am
malkomalko
This is a great tip!
I’ve been using this a lot to send data into adobe flex as the frontend and works beautifully. Instead of worrying about nesting, you can simply include which data you want, when you want it, and then use that data accordingly.
Smart and elegant.
November 20, 2008 at 3:57 am
MattFS218
Thanks for the information. I’m wondering if you know the syntax for including 2 different associated records, requiring nesting, and one not. I’ve tried a few combinations, but can’t seem to get any working :(
November 20, 2008 at 4:13 am
MattFS218
Never mind, stupid me figured it out :)
November 20, 2008 at 4:16 am
MattFS218
(:include=>{:user_group =>{ :include => [:keys] }, :user_datagrid_prefs => {}})
Works.
December 8, 2008 at 8:22 pm
Bruce Krysiak
Thanks, this was great. It turned out I also needed CamelCased names in my XML – I just submitted a patch (http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/1534) to give a :camelize option – please review & approve/comment if you’d like to see it make it in the core…