tollbooth
tollbooth

Reputation: 423

How can I simplify this Rails 3 controller method

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

Upvotes: 4

Views: 148

Answers (1)

Ekampp
Ekampp

Reputation: 755

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_withknows what mimes to respond to.

Upvotes: 1

Related Questions