Forum: Ruby on Rails to_xml associations and :only

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
3518ff338e5eee9b32eb1815daabc602?d=identicon&s=25 Marcelo Barbudas (Guest)
on 2008-10-28 16:17
(Received via mailing list)
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.
F47bebf5f4b10b709a59310027c8f977?d=identicon&s=25 Robert Zotter (Guest)
on 2008-10-29 19:00
(Received via mailing list)
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 Zotter
Zapient, LLC
Ruby on Rails Development and Consulting

http://www.zapient.com
http://www.fromjavatoruby.com
This topic is locked and can not be replied to.