Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redirect_to != return

I'm looking for some clarification regarding the behaviour of redirect_to.

I have this code:

if some_condition    redirect_to(path_one) end  redirect_to(path_two) 

If some_condition == true I get this error:

Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action.

It seems that the method continues to execute after the redirect_to call. Do I need to write code like this:

if some_condition    redirect_to(path_one)    return end  redirect_to(path_two) 
like image 334
ceth Avatar asked Apr 21 '11 11:04

ceth


People also ask

What does redirect_to return?

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.

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.


2 Answers

Yes, you need to return from method when doing redirect. It actually only adds appropriate headers for the response object.

You can write more rubyish way:

if some_condition     return redirect_to(path_one) end  redirect_to(path_two) 

or other way:

return redirect_to(some_condition ? path_one : path_two) 

or another way:

redirect_path = path_one  if some_condition     redirect_path = path_two end  redirect_to redirect_path 
like image 174
Eimantas Avatar answered Sep 27 '22 16:09

Eimantas


From http://api.rubyonrails.org/classes/ActionController/Base.html:

If you need to redirect on the condition of something, then be sure to add “and return” to halt execution.

def do_something   redirect_to(:action => "elsewhere") and return if monkeys.nil?   render :action => "overthere" # won't be called if monkeys is nil end 
like image 39
Vasiliy Ermolovich Avatar answered Sep 27 '22 17:09

Vasiliy Ermolovich