using redirect and if multiple times

My question is actually fairly simple, how do I make a create action which checks if a user is logged in, and if she/he is then redirect to the dashboard instead of rendering the index page where they've got links and stuff to go to and sign up. Also why is the code below not working.

class UsersController < ApplicationController

def new
  @user = User.new
end

def create
  if current_user.nil?
    redirect_to dplace_index_path
  if current_user
        @user = User.new(params[:user])
      if @user.save
          auto_login(@user)
          redirect_to dplace_index_path
  end
end
end
end
end

Answers


Your code isn't doing what you expect because the if statements are actually nested (you want elsif with this same structure -- or see my suggested fix below). Here's what your code, when properly formatted, actually looks like:

def create
  if current_user.nil?
    redirect_to dplace_index_path
    if current_user
      @user = User.new(params[:user])
      if @user.save
        auto_login(@user)
        redirect_to dplace_index_path
      end
    end
  end
end

Logically, you will never get down into the second if statement, because current_user must be nil to enter the first. Try something like this instead:

def create
  if current_user
    @user = User.new(params[:user])
    if @user.save
      auto_login(@user)
      redirect_to dplace_index_path
    end
  else
    redirect_to dplace_index_path
  end
end

I rearranged the code, but it should logically do what you want now. I put the "happy path" first (the current_user exists), and moved the redirect into the else statement.


General user authentication:

 def create
      user = User.find_by_email(params[:email])
      if user && user.authenticate(params[:password])
        session[:user_id] = user.id
        redirect_to dashboard_url, :notice => "Logged in!"
      else
        flash.now.alert = "Invalid email or password"
        render "new"
      end
    end

Try:

def create
  if current_user.blank? # .blank? will check both blank and nil
    # logic when user is not logged in
    redirect_to index_path
  else 
    # logic when user is logged in
    redirect_to dashboard_path
  end
end

def create
  redirect_to dplace_index_path unless current_user
  # no need to check current_user again
  @user = User.new(params[:user])
  if @user.save
    auto_login(@user)
    redirect_to dplace_index_path
  end
end

Need Your Help


About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.