簡體   English   中英

Redirect_to並使用return進行渲染

[英]Redirect_to and render with return

 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(...)並返回”的操作。

如果我使用return它將我帶到其他頁面,甚至不顯示flash msg。 如何解決這個問題?

每次在控制器中使用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

所以你得到了那個錯誤。 最簡單的解決方案是在調用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塊之后進行更多處理(如更新其他屬性或發送電子郵件)時,代碼的這些部分將不會被執行。

添加just and return在每個redirect_to的末尾and returnrender如下

`redirect_to @game_school  and return`  

這對你有用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM