Karthikds
Karthikds

Reputation: 247

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

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".

If I use return Its taking me to some other page, and even the flash msg is not shown. How to fix this?

Upvotes: 6

Views: 15232

Answers (2)

jvnill
jvnill

Reputation: 29599

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

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

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

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.

Upvotes: 8

Sachin R
Sachin R

Reputation: 11876

add justand return at the end of each redirect_to or render like below

`redirect_to @game_school  and return`  

This will work for you

Upvotes: 2

Related Questions