gpt4 book ai didi

ruby-on-rails - Redirect_to 和返回渲染

转载 作者:行者123 更新时间:2023-12-03 16:06:13 31 4
gpt4 key购买 nike

 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(...) and return”之类的操作。

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

最佳答案

每次使用 renderredirect在 Controller 中,剩余代码的任何部分都不应该有渲染或重定向,除非它确定它不会被传递。使用您的代码

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

所以你得到那个错误。最简单的解决方案是添加 return调用 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 block 之后进行更多处理(例如更新其他属性或发送电子邮件)时,那部分代码将不会被执行。

关于ruby-on-rails - Redirect_to 和返回渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15402605/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com