Redirect_to 并返回渲染 [英] 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
如果我正在执行此操作,则会收到错误
If I am executing this, I am getting error as
在此操作中多次调用渲染和/或重定向.请注意,您只能调用渲染或重定向,并且每个操作最多只能调用一次.还要注意,redirect和render都不会终止动作的执行,所以如果你想在重定向后退出一个动作,你需要做一些类似redirect_to(...)并返回"的事情.
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. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".
如果我使用 return 它带我到其他页面,甚至没有显示 flash msg.如何解决这个问题?
If I use return Its taking me to some other page, and even the flash msg is not shown. How to fix this?
推荐答案
每次在控制器中使用 render
或 redirect
时,其余代码的任何部分都不应该有渲染或重定向,除非确定它不会被传递.使用您的代码
everytime you use render
or redirect
in a controller, no part of the remaining code should have a render or redirect unless it's sure that it won't be passed. using your code
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 validation fails when you update the attributes, you're running render :invite_tutor_form
. But the code will keep on running the next part of the code which is
if redirect_with_msg
redirect_to @game_school, notice: "daw"
else
redirect_to @game_school
end
所以你会得到那个错误.最简单的解决方案是在调用 render
so you get that error. The simplest solution is to add a return
after the call to render
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 块之后进行更多处理(例如更新其他属性或发送电子邮件)时,将不会执行这些部分代码.
Please do note that when you're doing more processing (like updating other attributes, or sending emails) after the if block that contains return
, those part of the code will not be executed.
这篇关于Redirect_to 并返回渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!