我正在与下列作品合作;
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”,我做错了什么?
当我在DB中没有ID以显示“错误”时,我需要.我也试图使用救援ActiveRecord :: RecordNotFound但是一样的事情.
所有的帮助是赞赏.
解决方法
在救援块结束后的所有代码仅在救援模块中没有返回时被解释.所以你可以在你的救援行动结束时打电话给你.
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_from或rescue_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并不是很好的建议
原文地址:https://www.jb51.cc/ruby/265825.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。