# To\_xml associations and :only

**URL:** <https://www.ruby-forum.com/t/to-xml-associations-and-only/151971>\
**Category:** Rails\
**Created:** [October 28, 2008, 4:17pm UTC](https://www.ruby-forum.com/t/to-xml-associations-and-only/151971 "2008-10-28T16:17:42Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![arvias](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/ac91a4/32.png) [@arvias](https://www.ruby-forum.com/u/arvias)\
**Post date:** [October 28, 2008, 4:17pm UTC](https://www.ruby-forum.com/t/to-xml-associations-and-only/151971/1 "2008-10-28T16:17:42Z")

</div>

Hi,

A call to to\_xml(:only =\> [:field], :include =\> :association]) will  
filter the association result too(the resulting association will only  
have :field).

Is there a way around this?

I want to specify different filters for the main object and the  
association.

–  
M.

---

<div class="post-metadata">

**Author:** ![arvias](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/ac91a4/32.png) [@arvias](https://www.ruby-forum.com/u/arvias)\
**Post date:** [October 29, 2008, 7:00pm UTC](https://www.ruby-forum.com/t/to-xml-associations-and-only/151971/2 "2008-10-29T19:00:00Z")

</div>

Marcelo

Unfortunately like you mentioned when you use the :only options it  
will filter through all the associations as well. You can get around  
this by passing a proc to\_xml that appends the associations to the  
builder. For example we will take the ever so popular example of a  
User having many Posts.

class User  
has\_many :posts  
end

class Post  
belongs\_to :user  
end

user = User.first  
posts = user.posts  
post\_proc = lambda do |options|  
options[:builder] \<\< posts.to\_xml(:skip\_instruct =\> true)  
end

user.to\_xml(:only =\> :first\_name, :procs =\> post\_proc)

Make sure you have the :skip\_instruct =\> true option when you are  
creating the xml for your associations so it does not add the XML  
declaration \<?xml version="1.0 … \>

Cheers.

–  
Robert Z.  
Zapient, LLC  
Ruby on Rails Development and Consulting

[http://www.zapient.com](http://www.zapient.com)

> **[From Java To Ruby](http://www.fromjavatoruby.com)**
>
> and everything in between...
