views:

2456

answers:

3

I have an ActiveRecord model that I would like to convert to xml, but I do not want all the properties rendered in xml. Is there a parameter I can pass into the render method to keep a property from being rendered in xml?

Below is an example of what I am talking about.

def show
  @person = Person.find(params[:id])
  respond_to do |format|
    format.xml { render :xml => @person }
  end
end

produces the following xml

<person>
  <name>Paul</name>
  <age>25</age>
  <phone>555.555.5555</phone>
</person>

However, I do not want the phone property to be shown. Is there some parameter in the render method that excludes properties from being rendered in xml? Kind of like the following example

def show
  @person = Person.find(params[:id])
  respond_to do |format|
    format.xml { render :xml => @person, :exclude_attribute => :phone }
  end
end

which would render the following xml

<person>
  <name>Paul</name>
  <age>25</age>
</person>
+7  A: 

You can pass an array of model attribute names to the :only and :except options, so for your example it would be:

def show
  @person = Person.find(params[:id])
  respond_to do |format|
    format.xml { render :text => @person.to_xml, :except => [:phone] }
  end
end
John Topley
+1  A: 

The "render :xml" did not work, but the to_xml did work. Below is an example

def show
  @person = Person.find(params[:id])
  respond_to do |format|
    format.xml { render :text => @person.to_xml(:except => [:phone]) }
  end
end
Paul
+2  A: 

I just was wondering this same thing, I made the change at the model level so I wouldn't have to do it in the controller, just another option if you are interested.

model

class Person < ActiveRecord::Base
 def to_xml
  super(:except => [:phone])
 end
 def to_json
  super(:except => [:phone])
 end
end

controller

class PeopleController < ApplicationController
  # GET /people
  # GET /people.xml
  def index
    @people = Person.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @people }
      format.json  { render :json => @people }
    end
  end
end

I set one of them up for json and xml on every object, kinda convenient when I want to filter things out of every alternative formatted response. The cool thing about this method is that even when you get a collection back, it will call this method and return the filtered results.

efleming