views:

80

answers:

2

I'm looking to respond to XML. In my show action, I have something like this:

respond_to do |format|
  format.html {
    render :action => 'show'
  }
  format.xml {
    render :xml => @post.to_xml
  }
end

This will output all of the post's attributes. How would you go about outputting only some of the post's attributes. Also, say that Post belongs_to User. How would you then take this one step further by outputting the user's name with the post's XML (rather than the foreign key given to the post)?

+3  A: 
@post.to_xml(:except => [:foo, :bar], :include => :user)

The docs on to_xml go into more detail

Ben Hughes
This works well. However, if i use something like @post.to_xml(:only => [:created_at, :updated_at], :include => :user), the created_at and updated_at columns are displayed for both the post and the user. Is it possible to only specify the :created_at and :updated_at columns for the post - e.g. 'post.created_at'? Thanks for your help!
Homar
the documentation describes how to get access to the xml builder object for advanced uses. the :include option can also take a hash which specifies options that will go to the included items e.g. :include => {:user => {:only => :foo}}
Ben Hughes
A: 

Turns out that you can pass :only and :except options to the :include:

@post.to_xml(:only => [:created_at, :updated_at], :include => {:user => {:only => :name}})

This will get the created_at and updated_at columns for the post and the name for the associated user.

Homar