How can I simplify this Rails 3 controller method

I am currently using this method in the 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 I can reorganize this code to use response_with, but I'm not sure how to configure the output. Do I need to override the as_json and to_xml methods to configure the returned data? If I override these methods, will property associations be handled correctly? For example, there are many tenants and many contractors in the property. I may also have to return these items.

I would suggest that the controller method could be simplified to this.

 def show property = Property.find(params[:id]) respond_with(property) end 
+4
source share
1 answer

The respond_with method takes two arguments: resources* and a &block , so you can do this:

 def show property = Property.find(params[:id]) respond_with(property, :except => [:address1, :address2, :analysis_date, :analysis_date_2, ...]) end 

And remember, in order for us to respond_with we need to correctly add respond_to :html, :json, :xml to the top of your controller. So respond_with knows which memes to respond to.

+1
source

Source: https://habr.com/ru/post/1385300/


All Articles