Always use responds_to?
Until now I have always specified the format of the response for actions using a responds_to block, like so:
responds_to do |format|
format.js { render :json => @record }
end
Recently I realized that if you only support one format (as in the above example), you don't really need that block开发者_开发技巧. Is it best practice to leave it in, or remove it?
I'm going to differ with existing answers--I like to have a responds_to
block for all of my actions. I find that, while slightly more verbose, it more clearly self-documents the action. It also makes it easy to support additional formats in the future. Edit: another advantage is it acts as a gatekeeper. Any format not declared in the block is automatically served a "406 Not Acceptable"
I'm not really sure if this is best practice or not, but usually what I like to do is to leave the routes open to respond_to (i.e. by appending .:format
to the end), but only use it in the controllers when it's 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
That way, you aren't cluttering up your action_with_one_response
method with an unnecessary block, but you also have set yourself up quite nicely if you want to someday return your object in xml, json, etc.
I would say not to use respond_to unless you have multiple response types.
It is simply extra code to understand and for your app to process and handle:
render :json => @record
Is much more concise than:
responds_to do |format|
format.js { render :json => @record }
end
精彩评论