Always use responses_to?

So far, I have always specified the response format for actions using the responses_to block, for example:

responds_to do |format| format.js { render :json => @record } end 

I recently realized that if you support only one format (as in the example above), you really don't need this block. Is it best to leave it or delete it?

+6
ruby-on-rails
source share
3 answers

I will be distinguished by existing answers - I like to have a responds_to block for all my actions. I find that, although a little more detailed, it more clearly self-documents the action. It also simplifies support for additional formats in the future. Edit: Another advantage is that it acts as a gatekeeper. Any format not declared in the block is automatically served by "406 invalid"

+2
source share

I'm not sure if this is the best practice or not, but I usually like to leave routes open for response_to (i.e. by adding .:format to the end), but use it only in controllers when necessary.

Example:

routes.rb

 map.connect :controller/:action/:id.:format 

model_controller.rb

 # Return a collection of model objects def action_with_multiple_responses @models = Model.all respond_to do |format| format.html #=> action_with_multiple_responses.html format.xml { render :xml => @models } end end # Return the first model object def action_with_one_response @model = Model.first end 

This way you are not cluttering up your action_with_one_response method action_with_one_response unnecessary block, but you are also very well proven if you want to ever return your object to xml, json, etc.

0
source share

I would say that you should not use response_to unless you have several types of answers.

This is just additional code to understand and process and process for your application:

 render :json => @record 

Much shorter than:

 responds_to do |format| format.js { render :json => @record } end 
0
source share

All Articles