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