2013-01-23 25 views
-1

我的問題其實很簡單,我如何做一個創建操作,檢查用戶是否登錄,如果她/他然後重定向到儀表板而不是呈現索引頁在哪裏他們有鏈接和東西去註冊。此外,爲什麼下面的代碼無法正常工作。使用重定向和如果多次

類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 
+0

你得到的錯誤是什麼? –

回答

0

一般用戶認證:

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 
+0

我有點覺得上面的答案更簡單一些。無論如何,雖然:) – MrBobMcQlurk

+0

很高興知道:) –

0

嘗試:

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 
1

你的代碼是不是做你期望,因爲if語句是 實際上是嵌套的(你想要elsif具有相同的結構 - 或者參見下面的建議修正)。這裏是你的代碼,正確格式化的時候,其實是這樣的:

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 

從邏輯上講,你將永遠不會降入第二if語句,因爲current_user必須nil進入第一。嘗試這樣的代替:

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 

我重新安排了代碼,但它應該邏輯上做你想要的東西。我首先將「開心路徑」(存在current_user),並將重定向移到else語句中。

+0

在這種情況下,「current_user」必須是真實的,我不希望這一點。所以「elsif」是一個首選和好方法? – MrBobMcQlurk

+0

'current_user'不一定是'true' - 它只需要「truthy」。當'current_user'被設置爲一個用戶對象時,它將通過'if current_user'條件評估爲'true'。當'current_user'爲'nil'時(這是你最初檢查的內容),'如果current_user'將計算爲'false'並落入else語句。在你的代碼中使用'elsif'沒有什麼問題,但是在這個例子中沒有必要。合理? – Cade

0
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 
+0

真的嗎?!我有點覺得沒有具體說明可能導致其他人的某種利用,比如黑客等?你確定? – MrBobMcQlurk

+0

我可以將其添加到新操作中而不是創建操作中。那會導致某種利用可能性嗎? – MrBobMcQlurk

+0

即使沒有這個代碼,這個代碼的確會繼續執行其餘的動作current_user –