petfreshman
petfreshman

Reputation: 523

Rails executing if and else statements

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

Upvotes: 0

Views: 200

Answers (1)

Vlad Bogomolov
Vlad Bogomolov

Reputation: 358

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.

Upvotes: 2

Related Questions