我正在与下列作品合作;
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并不是很好的建议