Redirect_to并使用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 

如果在更新属性时validation失败,则表示您正在运行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` 

这对你有用