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?
A respond_to shortcut it works the same way as writing the full respond_to block in index . It's a short way to tell Rails about all the formats your action knows about. And if different actions support different formats, this is a good way to handle those differences without much code.
respond_to is a Rails method for responding to particular request types.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With