Rails executing if and else statements

Go To StackoverFlow.com

0

I am trying to set up an email verification process in my application and I generate a token just fine and emails to the user when they sign up. But when I click on the verification link, both the if and else statements in the 'users_controller/confirm' action are executed. I am redirected to root_path but the two fields in the user record are modified. When I run find_by_token from the rails console, it returns the expected user. I am using mysql and am wondering if there is some kind of latency in the query that would cause both to execute.

  def confirm
    if User.find_by_token(params[:token]).nil?
      redirect_to root_path
    else
      @user = User.find_by_token(params[:token])
      cookies[:auth_token] = @user.auth_token
      User.skip_callbacks = true
      @user.update_attribute(:token, "")
      @user.update_attribute(:confirmed, 1)
      User.skip_callbacks = false
      reset_session
      redirect_to routes_path
    end
  end
2012-04-03 20:29
by petfreshman
That seems extremely unlikely. I would suggest adding some output to each branch of the conditional, so that you can see which one gets executed - MrTheWalrus 2012-04-03 21:02
is this cut'n'pasted code, or did you re-type it? (I'm just wondering if you have a typo in the real code that isn't here if you've re-typed... - Pavling 2012-04-03 22:06
Agreed - this code should work as expected. If the actual code is subtly different, just be aware that calling redirect_to does not stop execution of the action - you need to return after it to enforce that - Thilo 2012-04-05 08:13


2

You can use before filter to check and redirect like this

  before_filter :find_user

  def confirm
    #your action code
  end

  private
  def find_user
    @email = User.find_by_token params[:token].to_s
    redirect_to root_path, notice: 'Your token is wrong!' if @email.nil?
  end

This way, the code of your action will run only for valid record.

2012-04-05 06:38
by Vladson
This wasn't the issue, but it got me on the right track. The else block was executing and the cookie was being created, but destroyed as soon as token was set to blank due to a helper method I had. Thanks for your help - petfreshman 2012-04-20 15:14