ruby-on-rails – 在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”,我做错了什么?

当我在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_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并不是很好的建议

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...