Ruby-on-rails 在 Rails 中使用救援

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2567133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:29:19  来源:igfitidea点击:

work with rescue in Rails

ruby-on-railsrubyrescue

提问by Adnan

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?

现在,无论我是否拥有正确的 ID,无论我是否拥有正确的 ID,我总是觉得“OK”,我做错了什么?

I need that when I have no ID in the DB to show "ERROR". I have also tried to use rescue ActiveRecord::RecordNotFoundbut same happens.

当我在数据库中没有 ID 时需要显示“错误”。我也尝试使用,rescue ActiveRecord::RecordNotFound但同样发生。

All help is appreciated.

感谢所有帮助。

回答by shingara

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.

只有当救援块中没有返回时,救援块结束之后的所有代码才会被解释。所以你可以在你的救援块结束时调用 return 。

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

or

或者

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

But in your case the better is to use rescue_fromor rescue_in_public

但在你的情况下,最好使用rescue_fromrescue_in_public

like

喜欢

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

But the using of rescue_in_public is not really good advice

但是使用rescue_in_public 并不是很好的建议

回答by FastSolutions

Just an overall Rails Rescue answer:

只是一个整体的 Rails Rescue 答案:

I found this to be very cool:

我发现这很酷:

@user = User.find(params[:id])  rescue ""

回答by yfeldblum

If there is no userwith that id, then User.findwill return nil. Returning nilis not an error case and will not trigger a rescue.

如果没有user跟那个id,那么User.find就会返回nil。返回nil不是错误情况,也不会触发rescue.