2013-11-14 26 views
3

我想重定向用戶,當出現錯誤時,救援似乎在重定向後調用。重定向和返回有什麼區別?或者發生了什麼?救援錯誤和在rails中重定向

用戶模型中

def self.find_by_credentials(user_name,password) 
    user = User.find_by_user_name(user_name) 
    msg = 'User Not Found' 
    raise StandardError, msg unless user 
    msg = 'Invalid Login' 
    raise StandardError, msg unless user.is_password?(password) 

    user 
    end 
在會話控制器

def create 
    begin 
     user = User.find_by_credentials(
     params[:user][:user_name], 
     params[:user][:password] 
    ) 

    rescue StandardError => e 
     flash.now[:errors] = e.message 
     redirect_to new_user_url 
    end 

    login_user!(user) 
    end 

回答

1

以MrDanA的意見,我結束返回我發現了一種我覺得很舒服和有效的風格。

class SessionsController < ApplicationController 

    def create 
    begin 
     @user = User.authenticate!(
     params[:user] 
    ) 
     redirect_to root_url 
    rescue StandardError => e 
     flash.now[:error] = "Invalid Login" 
     render :new 
    end 
    end 

這樣我就可以將認證邏輯留在用戶模型中,而且bang會讓錯誤決定如何繼續。

0

添加在救援的解決了這個

+1

'redirect_to'不會導致該方法停止運行並開始重定向。 'return'是一個Ruby關鍵字,它停止了方法。在這種情況下,你應該做的就是將'login_user!(user)'部分放在'begin'內,因爲這是它唯一發生的時間 - 這給你更好的程序控制/流而不是隨機的'return'在你的方法中間。 – MrDanA