use*_*573 4 controller before-filter rescue ruby-on-rails-3
我的控制器中有两种方法用于查找用户(注意范围enabled_only):
before_filter :find_user, :only => :show
before_filter :find_any_user, :only => [:edit, :update, :destroy]
def find_user
@user = User.enabled_only.find(params[:id])
rescue ActiveRecord::RecordNotFound
flash[:alert] = "The user you were looking for could not be found"
redirect_to root_path
end
def find_any_user
@user = User.find(params[:id])
rescue ActiveRecord::RecordNotFound
flash[:alert] = "The user you were looking for could not be found"
redirect_to root_path
end
Run Code Online (Sandbox Code Playgroud)
当然,这些可以合并到一种检查是否存在错误的方法中,:action == 'show'但我无法采取救援措施来捕获错误。我尝试了类似以下的方法,但没有成功:
before_filter :find_user, :only => [:show, :edit, :update, :destroy]
def find_user
@user = if :action == 'show'
User.enabled_only.find(params[:id])
else
User.find(params[:id])
end
rescue ActiveRecord::RecordNotFound
flash[:alert] = "The user you were looking for could not be found"
redirect_to root_path
end
Run Code Online (Sandbox Code Playgroud)
请告知如何做到这一点。
谢谢
您需要将要“保护”的代码包装在 abegin和 a之间rescue
before_filter :find_user, :only => [:show, :edit, :update, :destroy]
def find_user
begin
@user = if :action == 'show'
User.enabled_only.find(params[:id])
else
User.find(params[:id])
end
rescue ActiveRecord::RecordNotFound
flash[:alert] = "The user you were looking for could not be found"
redirect_to root_path
end
end
Run Code Online (Sandbox Code Playgroud)
顺便说一句,你的测试:action == 'show'永远不可能是真的。:action是一个符号,其值为:action,其值永远不会改变,同样对于'show',其值也永远不会改变。我不确定实现这一目标的最佳方法是什么,但你可以这样做,但你可以这样做if params[:action] == "show"