【问题标题】:Redirect_to and render with returnRedirect_to 和返回渲染
【发布时间】:2013-03-14 06:27:05
【问题描述】:
 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和render都不会终止action的执行,所以如果你想在redirect后退出一个action,你需要做一些类似“redirect_to(...) and return”的操作。

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

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    每次在控制器中使用render 或redirect 时,其余代码的任何部分都不应进行渲染或重定向,除非确定不会通过。使用您的代码

    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
    

    所以你得到了那个错误。最简单的解决方案是在调用render之后添加一个return

    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 块之后进行更多处理(例如更新其他属性或发送电子邮件)时,这部分代码将不会被执行。

    【讨论】:

    • 如果你使用redirect_to,你还需要return吗?
    • 如果您在before_action 中使用redirect_to,则例外。如果您的重定向发生在您的操作之前,则无需返回。
    【解决方案2】:

    在每个redirect_to 或render 的末尾添加and return,如下所示

    `redirect_to @game_school  and return`  
    

    这对你有用

    【讨论】:

    猜你喜欢
    • 2015-01-31
    • 2018-09-01
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多