ruby-on-rails-3 – rails如果检查失败然后救援
发布时间:2020-12-17 02:32:51 所属栏目:百科 来源:网络整理
导读:我的控制器中有2个方法用于查找用户(请注意enabled_only范围): before_filter :find_user,:only = :showbefore_filter :find_any_user,:only = [:edit,:update,:destroy]def find_user @user = User.enabled_only.find(params[:id])rescue ActiveRecord::Re
我的控制器中有2个方法用于查找用户(请注意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 当然,这些可以合并为一种方法,检查是否:action ==’show’但是我无法得到救援来捕获错误.我试过类似下面的东西,但它不起作用: before_filter :find_user,:only => [:show,:edit,: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 请告知如何做到这一点. 谢谢 解决方法
您需要在开始和救援之间包装您想要“保护”的代码
before_filter :find_user,: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 顺便提一下你的测试:action ==’show’永远不会成真. :action是一个符号,其值是:action,它的值永远不会改变,同样对于’show’,它的值永远不会改变.我不确定实现这个目标的最佳方法是什么,但是你可以做但如果params [:action] ==“show”你可以做到 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |