wyc
wyc

Reputation: 55263

Redirection based on the current controller's action

Right now, I have two views that are using the users#create action: users/new.thml.erb and enter_email.html.erb.

The problem is that with the current code, the user is redirected to new.html.erb when the form in enter_email.html.erb has a validation error. So I tried this:

  def create
    @user = User.new(params[:user])
    if @user.save
      sign_in @user
      flash[:success] = "Welcome to the Sample App!"
      redirect_to @user
    else
      if params[:action] == "enter_email"
        render 'enter_email'
      else
        render 'new'
      end
    end
  end

I wanted to user to be redirected to enter_email.html.erb when the action is 'enter_email'. But I'm still being redirected to 'new.html.erb'.

Any suggestions to fix this? (it is because the action being performed is actually create? If so, how to modify the code to make the redirection work?)

Upvotes: 1

Views: 96

Answers (2)

rewritten
rewritten

Reputation: 16435

I see a couple of ways to do it:

  • Add a hidden field to both forms, and check in params for the value of that field, so you know which form you come from

    # in your new.html.erb view
    hidden_field_tag 'form_name', 'new'
    
    # in your enter_email.html.erb view
    

      hidden_field_tag 'form_name', 'enter_email'

    # in controller
    if params[:form_name] == "enter_email"
      render 'enter_email'
    else
      render 'new'
    end
    
  • Use a different action for creation, like create_from_enter_email, and direct the enter_email form to it.

Upvotes: 3

Chris Salzberg
Chris Salzberg

Reputation: 27374

As you thought, the problem is that the action is create and not enter_email, so the if/else conditional always goes to the else branch and the new view is rendered.

To render the previous view, you can use request.referrer as suggested in this answer:

def create
  @user = User.new(params[:user])
  if @user.save
    sign_in @user
    flash[:success] = "Welcome to the Sample App!"
    redirect_to @user
  else
    if request.referrer == root_url
      render 'enter_email'
    else
      render 'new'
    end
  end
end

I'm checking if request.referrer is root_url based on the fact that the login partial is on the homepage (which you mention in the comments below). This should work.

Upvotes: 2

Related Questions