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>
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
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.
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
The except is good, but you have to remember to put it everywhere. If you're putting this in a controller, every method needs to have an except clause. I overwrite the serializable_hash method in my models to exclude what I don't want to show up. This has the benefits of not having t put it every place you're going to return as well as also applying to JSON responses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With