gpt4 book ai didi

ruby-on-rails-3 - rails 如果其他检查失败则救援

转载 作者:行者123 更新时间:2023-12-04 07:03:08 25 4
gpt4 key购买 nike

我的 Controller 中有 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, :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

请告知如何做到这一点。

谢谢

最佳答案

您需要将要“保护”的代码包装在 begin 之间和一个 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

顺便说一下你的测试 :action == 'show'永远不可能是真的。 :action是一个符号,其值为 :action ,它的值永远不会改变,与 'show' 相同,它的值永远不会改变。我不确定实现这一目标的最佳方法是什么,但您可以这样做,但您可以这样做 if params[:action] == "show"

关于ruby-on-rails-3 - rails 如果其他检查失败则救援,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13130684/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com