在 Rails 中参与救援工作
我正在创作以下作品;
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
但同样的情况发生。
感谢所有帮助。
I am working with the following piece;
def index
@user = User.find(params[:id])
rescue
flash[:notice] = "ERROR"
redirect_to(:action => 'index')
else
flash[:notice] = "OK"
redirect_to(:action => 'index')
end
Now I either case whether I have a correct ID or not, I am always getting "OK" in my view, what am I doing wrong?
I need that when I have no ID in the DB to show "ERROR". I have also tried to use rescue ActiveRecord::RecordNotFound
but same happens.
All help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
仅当救援块中没有返回时,才会解释救援块结束后的所有代码。所以你可以在救援块结束时调用 return 。
或
但就您而言,最好使用 rescue_from 或 < a href="http://api.rubyonrails.org/classes/ActionController/Rescue.html#M000415" rel="noreferrer">rescue_in_public
之类的
但是使用rescue_in_public并不是一个很好的建议
All code after the end of the rescue block is interpreted only if there are no returns in the rescue block. So you can call return at the end of your rescue block.
or
But in your case the better is to use rescue_from or rescue_in_public
like
But the using of rescue_in_public is not really good advice
只是 Rails Rescue 的总体答案:
我发现这非常酷:
Just an overall Rails Rescue answer:
I found this to be very cool:
如果没有具有该
id
的user
,则User.find
将返回nil
。返回nil
不是错误情况,也不会触发救援
。If there is no
user
with thatid
, thenUser.find
will returnnil
. Returningnil
is not an error case and will not trigger arescue
.