Custom to_xml

I have two models: ledger and label. A ledger can contain many labels.

Here is the xml returned from http://localhost/ledgers/78.xml:

<ledger>   <account-id type="integer">11</account-id>   <amount type="decimal">30.0</amount>   <check-number/>   <created-on type="date">2007-10-22</created-on>   <date type="date">2007-10-22</date>   <description>Deposit</description>   <id type="integer">78</id> </ledger>

Question:

How can I return the labels associated with the ledger? The xml should look like this (notice the "labels" addition):

<ledger>   <account-id type="integer">11</account-id>   <amount type="decimal">30.0</amount>   <check-number/>   <created-on type="date">2007-10-22</created-on>   <date type="date">2007-10-22</date>   <description>Deposit</description>   <id type="integer">78</id>   <labels>     <label>Food</label>     <label>Music</label>   </labels> </ledger>

I just figured it out.

Instead of this: format.xml { render :xml => @ledger.to_xml }

do this: format.xml { render :xml => @ledger.to_xml(:include => [ :labels ]) }

Works like a charm. :slight_smile:

FYI I found the answer here: http://api.rubyonrails.org/classes/ActiveRecord/XmlSerialization.html#M000910