I doubt that if between both commands there's a difference, when I want to create an action without a view in rails I've always used redirect_to
with no return after it and I've never had any problems, but until I forgot to put the redirect_to
I realized that rails recommend to do a redirect_to and return
if I don't want to have a view for the action, then I wonder, is there any difference when adding the return?, at least in my case I have never noticed any difference or error.
redirect_to is not return Keep in mind that redirect_to does not cause the action to stop executing. It is not like calling return in a Ruby method.
There is an important difference between render and redirect_to: render will tell Rails what view it should use (with the same parameters you may have already sent) but redirect_to sends a new request to the browser.
Rails's redirect_to takes two parameters, option and response_status (optional). It redirects the browser to the target specified in options. This parameter can be: Hash - The URL will be generated by calling url_for with the options.
In Rails 4. x, for going back to previous page we use redirect_to :back. However sometimes we get ActionController::RedirectBackError exception when HTTP_REFERER is not present. This works well when HTTP_REFERER is present and it redirects to previous page.
redirect_to
will cause any automatic rendering to be skipped.
You only need the 'return' if you need to bypass further code in the action. If the further code does an explicit render
, then you must do a return
to avoid an error of redirect and render both being present.
For example, a typical pattern in an update
action might be...
def update
@record = Record.new(record_params)
if @record.save
flash[:success] = "record was successfully saved"
redirect_to records_path
return
end
flash.now[:error] = "please fix the problems in the record"
render :edit
end
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