gpt4 book ai didi

ruby-on-rails - 在 Rails 中使用 rescue

转载 作者:数据小太阳 更新时间:2023-10-29 06:40:19 25 4
gpt4 key购买 nike

我正在处理以下作品;

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 时,我需要它来显示“错误”。我也尝试过使用 rescue ActiveRecord::RecordNotFound 但同样的事情发生了。

感谢所有帮助。

最佳答案

仅当救援 block 中没有返回时,才解释救援 block 结束后的所有代码。因此,您可以在救援 block 的末尾调用 return。

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_fromrescue_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 并不是很好的建议

关于ruby-on-rails - 在 Rails 中使用 rescue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2567133/

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