I currently have this method in a controller:
def show
property = Property.find(params[:id])
respond_to do |format|
format.xml { render :xml => property.to_xml(:except => [:address1, :address2, :analysis_date, :analysis_date_2, ...]) }
format.json { render :json => property.to_json(:except => [:address1, :address2, :analysis_date, :analysis_date_2, ...]) }
end
end
It seems like I can refactor this code to use respond_with, but I am not sure how to customize the output. Do I need to override the as_json and to_xml methods in order to customize the returned data? If I override these methods, will property associations still be handled correctly? For example, a property has many tenants and many contractors. I may need to return those elements as well.
I would assume the controller method could then be simplified to this.
def show
property = Property.find(params[:id])
respond_with(property)
end
The respond_with
method takes two arguments: the resources*
and a &block
so you should be able to do this:
def show
property = Property.find(params[:id])
respond_with(property, :except => [:address1,
:address2,
:analysis_date,
:analysis_date_2,
...])
end
And just remember, that in order to us respond_with
properly you need to add respond_to :html, :json, :xml
in the top of your controller. So that respond_with
knows what mimes to respond to.