Homar
Homar

Reputation: 1519

Rails: Responding to XML

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)?

Upvotes: 1

Views: 1888

Answers (2)

Homar
Homar

Reputation: 1519

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.

Upvotes: 1

Ben Hughes
Ben Hughes

Reputation: 14185

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

The docs on to_xml go into more detail

Upvotes: 4

Related Questions