Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redirect_to vs redirect_to and return

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.

like image 684
Patricio Sard Avatar asked Jan 17 '16 19:01

Patricio Sard


People also ask

Does redirect_to return?

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.

What is difference between render and redirect in Rails?

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.

What is redirect_to in Ruby?

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.

How do I redirect back in rails?

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.


1 Answers

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
like image 162
SteveTurczyn Avatar answered Sep 29 '22 00:09

SteveTurczyn