2011-04-21 66 views
57

我只想給出有關redirect_to行爲的確認。redirect_to!= return

我有代碼看起來像:

if some_condition 
    redirect_to(path_one) 
end 

redirect_to(path_two) 

如果some_condition =真正的我得到錯誤:

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.

看來這個方法繼續redirect_to的調用後執行。我是否需要創建如下代碼:

if some_condition 
    redirect_to(path_one) 
    return 
end 

redirect_to(path_two) 

回答

88

是的,你需要做的重定向時從方法返回。它實際上只爲響應對象添加適當的標頭。

你可以寫更多rubyish方式:

if some_condition 
    return redirect_to(path_one) 
end 

redirect_to(path_two) 

或其他方式:

return redirect_to(some_condition ? path_one : path_two) 

或另一種方式:

redirect_path = path_one 

if some_condition 
    redirect_path = path_two 
end 

redirect_to redirect_path 
29

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 
+1

+1 for RTFM ;-) – spume 2014-04-09 16:37:34

+2

如果爲了更好地構建代碼,將重定向放在控制器中的私有'helper'方法中。我假設私人方法內的返回形式不會完成這項工作,對嗎?處理這個問題的慣用方法是什麼?或者是否必須將所有重定向放在控制器操作的頂層? – pitosalas 2014-04-29 22:49:45

+3

@pitosalas請參閱http://guides.rubyonrails.org/action_controller_overview.html#filters。它說'如果之前「過濾器呈現或重定向之前,行動將不會運行。' – 2014-05-01 17:35:49

23

你也可以做

redirect_to path_one and return 

這很好看。

+0

如果redirect_to返回false或nil,會發生什麼情況?這不意味着退貨聲明不會被執行嗎?或者這是意圖? redirect_to文檔不指定它的返回值是什麼。 – dbeachy1 2017-09-15 15:47:18

1

值得一提的還有沒有需要return除非你redirect_to後有任何代碼,如下例所示:

def show 
    if can?(:show, :poll) 
    redirect_to registrar_poll_url and return 
    elsif can?(:show, Invoice) 
    redirect_to registrar_invoices_url and return 
    end 
end 
1

鞏固Eimantas' answer兩行代碼的「rubyish方式」的例子:

return redirect_to(path_one) if some_condition 

redirect_to(path_two)