2013-03-14 71 views
5
def confirm_invite_new_tutor 
    redirect_with_msg = false 
    @game_school = GameSchool.find(params[:id]) 
    existing_user_emails = params[:all_emails][:existing_user] || [] 
    new_users = params[:param_game_school][:game_school_invites_attributes] 

if existing_user_emails.present? 
     existing_user_emails.each do |existing_user| 
     // some code 
     end 
     redirect_with_msg = true 
    end 
    if new_users.present? 
     if @game_school.update_attributes(params[:param_game_school]) 
     redirect_with_msg = true 
     else 
     render :invite_tutor_form 
     end 
    end 
    if redirect_with_msg 
     redirect_to @game_school, notice: "daw" 
    else 
     redirect_to @game_school 
    end 
    end 

如果我执行此,我得到错误的redirect_to时与返回渲染

渲染和/或重定向在这次行动被称为多次。请注意,您只能调用渲染或重定向,并且每次最多只能调用一次。另外请注意,重定向和呈现都不会终止该动作的执行,因此如果您想在重定向后退出动作,则需要执行诸如“redirect_to(...)并返回”之类的操作。

如果我使用返回它带我到其他页面,甚至没有显示flash msg。 如何解决这个问题?

回答

1

在每个redirect_torender年底仅增加and return像下面

`redirect_to @game_school and return` 

这会为你工作

+2

redirect_to xyz && return怎么样? – Lee 2014-04-05 10:10:40

+1

在优先级上,'和'和'&&'(lol)在Ruby中有两个非常不同的含义(请参阅http://ruby-doc.org/core-2.3.0/doc/syntax/precedence_rdoc.html)。在这种情况下,你应该使用'和'。这也是该主题的另一个有趣资源:http://devblog.avdi.org/2014/08/26/how-to-use-rubys-english-andor-operators-without-going-nuts/ – lucke84 2016-03-17 11:20:05

8

每次你在一个控制器使用renderredirect,没有剩余的部分代码应有一个渲染或重定向,除非它确定它不会被传递。使用你的代码

if new_users.present? 
    if @game_school.update_attributes(params[:param_game_school]) 
    redirect_with_msg = true 
    else 
    render :invite_tutor_form 
    end 
end 

如果验证,当您更新的属性失败,你正在运行render :invite_tutor_form。但代码将继续运行代码的下一部分,这是

if redirect_with_msg 
    redirect_to @game_school, notice: "daw" 
else 
    redirect_to @game_school 
end 

所以你会得到那个错误。最简单的办法是在调用之后添加一个returnrender

if new_users.present? 
    if @game_school.update_attributes(params[:param_game_school]) 
    redirect_with_msg = true 
    else 
    render :invite_tutor_form 
    return 
    end 
end 

请你注意,当你做更多的处理(如更新的其他属性,或发送电子邮件),它包含return if块之后,那些部分代码将不会被执行。

+0

如果您使用'redirect_to'你还需要'return'吗? – barnett 2014-10-22 16:06:01

+1

是的,你不能在同一个动作中有两个。 – jvnill 2014-10-23 00:21:08

+0

如果您在'before_action'中使用'redirect_to',则会出现异常。 如果您的重定向发生在您的操作之前,则不需要执行退货。 – saneshark 2016-01-05 06:36:13