【问题标题】:Ruby Exception - If Statement rescue doesn't handling exceptionRuby 异常 - 如果语句救援不处理异常
【发布时间】:2012-04-15 00:14:01
【问题描述】:

大家,我在处理 ruby​​ 中的异常时遇到了一些问题。我不明白为什么我的陈述不起作用。

错误:找不到 id=14 的用户 我想重定向到登录页面。

 def login_required
    begin
      if session[:user_id] == nil
        redirect_to login_path, :notice => "You are not logged"
      elsif  User.find(session[:user_id])
        return nil
      end
    rescue ActiveRecord::RecordNotFound
      redirect_to login_path, :notice => "No user corresponding in database"
    end
  end

希望你能帮助我。

谨此, 奥宾

【问题讨论】:

  • 不相关,但 IMO 在此处返回 nil 具有误导性。

标签: ruby-on-rails ruby exception rescue


【解决方案1】:
def login_required
  begin
  if session[:user_id] == nil
    redirect_to login_path, :notice => "You are not logged"
  elsif  User.find_by_id(session[:user_id]).nil?
    #rescue ActiveRecord::RecordNotFound (use if u want to use User.find)
    redirect_to login_path, :notice => "No user corresponding in database"
    return nil
  end

end

结束

【讨论】:

  • 此代码不起作用。我仍然有异常:TasksController#index 中的 ActiveRecord::RecordNotFound - 找不到 id=14 的用户。我不知道如何处理这个异常..
  • 如果您在 TasksController 的索引操作中使用 User.find,然后使用 User.find_by_id(session[:user_id]) 如上所示。
  • 你知道为什么 find_by_id 不处理异常 RecordNotFound 吗?
  • find_by_id 返回 nil。它不会像 find 那样在找不到记录时引发异常。
【解决方案2】:

这不起作用的唯一原因是 ActiveRecord 实际上正在查找一行

User.find(session[:user_id])

尝试记录 session[:user_id] 并使用 SQL 查看 DB。

另一方面,您可以使用

session[:user_id].nil?

而不是

session[:user_id] == nil

【讨论】:

  • 在 SQL select * from users where id = 15 中什么也不返回。在 TasksController#index 中使用我的代码 ActiveRecord::RecordNotFound - 找不到 id=14 的用户。谢谢你的零提示。
  • 那么您的 TasksController#index 中的内容可以提供该代码吗?
【解决方案3】:

我会重写你的方法如下:

def login_required

 return redirect_to(login_path, 
   :notice => "You are not logged") if session[:user_id].blank?

 user = User.find_by_id(session[:user_id])
 return user if user.present?
 redirect_to login_path, :notice => "No user corresponding in database" 
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-18
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    相关资源
    最近更新 更多