在Rails中使用救援工作

我正在使用以下作品;

def index @user = User.find(params[:id]) rescue flash[:notice] = "ERROR" redirect_to(:action => 'index') else flash[:notice] = "OK" redirect_to(:action => 'index') end 

现在我要么是否有正确的ID,我总是在我看来“OK”,我做错了什么?

当数据库中没有ID显示“ERROR”时,我需要这样做。 我也试过使用rescue ActiveRecord::RecordNotFound但同样的事情发生了。

所有帮助表示赞赏。

仅当救援块中没有返回时,才解释救援块结束后的所有代码。 因此,您可以在救援区块的末尾致电返程。

 def index begin @user = User.find(params[:id]) rescue flash[:notice] = "ERROR" redirect_to(:action => 'index') return end flash[:notice] = "OK" redirect_to(:action => 'index') end 

要么

 def index @user = User.find(params[:id]) # after is interpret only if no exception before flash[:notice] = "OK" redirect_to(:action => 'index') rescue flash[:notice] = "ERROR" redirect_to(:action => 'index') end 

但在你的情况下,更好的是使用rescue_from或rescue_in_public

喜欢

 class UserController < ApplicationController def rescue_in_public(exception) flash[:notice] = "ERROR" redirect_to(:action => 'index') end def index @user = User.find(params[:id]) flash[:notice] = "OK" redirect_to(:action => 'index') end end 

但是使用rescue_in_public并不是一个很好的建议

只是一个整体的Rails Rescue答案:

我发现这很酷:

 @user = User.find(params[:id]) rescue "" 

如果没有具有该id user ,则User.find将返回nil 。 返回nil不是错误情况,不会触发rescue