ruby-on-rails-3 – rails如果检查失败然后救援

ruby-on-rails-3 – rails如果检查失败然后救援,第1张

概述我的控制器中有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[ 我的控制器中有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::RecordNotFound  flash[:alert] = "The user you were looking for Could not be found"  redirect_to root_pathenddef 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_pathend

当然,这些可以合并为一种方法,检查是否: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])  endrescue ActiveRecord::RecordNotFound  flash[:alert] = "The user you were looking for Could not be found"  redirect_to root_pathend

请告知如何做到这一点.

谢谢

解决方法 您需要在开始和救援之间包装您想要“保护”的代码

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  endend

顺便提一下你的测试:action ==’show’永远不会成真. :action是一个符号,其值是:action,它的值永远不会改变,同样对于’show’,它的值永远不会改变.我不确定实现这个目标的最佳方法是什么,但是你可以做但如果params [:action] ==“show”你可以做到

总结

以上是内存溢出为你收集整理的ruby-on-rails-3 – rails如果检查失败然后救援全部内容,希望文章能够帮你解决ruby-on-rails-3 – rails如果检查失败然后救援所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1279516.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-09
下一篇 2022-06-09

发表评论

登录后才能评论

评论列表(0条)

保存