在Rails中进行救援 [英] work with rescue in Rails

查看:98
本文介绍了在Rails中进行救援的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理以下内容;

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

现在不管我是不是我的ID是否正确,我总是看到"OK",我在做什么错了?

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?

当数据库中没有ID时,我需要显示"ERROR".我也尝试过使用rescue ActiveRecord::RecordNotFound,但同样会发生.

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 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.

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_in_public

But in your case the better is to use rescue_from or 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并不是一个很好的建议

But the using of rescue_in_public is not really good advice

这篇关于在Rails中进行救援的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆