【问题标题】:work with rescue in Rails在 Rails 中使用救援
【发布时间】:2010-04-02 14:28:10
【问题描述】:

我正在处理以下作品;

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”,我做错了什么?

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

感谢所有帮助。

【问题讨论】:

  • 这是来自您应用的实际代码吗?就目前而言,您似乎正在重定向回相同的操作(索引),这将导致无限循环。

标签: ruby-on-rails ruby rescue


【解决方案1】:

只有在救援块中没有返回时,救援块结束后的所有代码才会被解释。所以你可以在你的救援块结束时调用 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

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并不是一个很好的建议

【讨论】:

    【解决方案2】:

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

    我觉得这很酷:

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

    【讨论】:

      【解决方案3】:

      如果没有userid,那么User.find 将返回nil。返回nil 不是错误情况,也不会触发rescue

      【讨论】:

      • 我很确定这是不对的。具有无效 ID 的 find 将引发 ActiveRecord::RecordNotFound。如果您使用其中一种动态查找器,例如User.find_by_name 的值与记录不匹配,则将返回 nil。见api.rubyonrails.org/classes/ActiveRecord/Base.html#M002263
      • 好吧,先生,我检查过,您是正确的。谢谢你。 OP 中的 find 调用实际上应该引发,除非代码实际上是 User.find(:first, params[:id])
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-12
      • 2023-01-13
      • 1970-01-01
      • 1970-01-01
      • 2014-11-08
      相关资源
      最近更新 更多