Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 处理ActiveRecord结果-未找到任何记录_Ruby On Rails_Ruby On Rails 3_Activerecord - Fatal编程技术网

Ruby on rails 处理ActiveRecord结果-未找到任何记录

Ruby on rails 处理ActiveRecord结果-未找到任何记录,ruby-on-rails,ruby-on-rails-3,activerecord,Ruby On Rails,Ruby On Rails 3,Activerecord,当ActiveRecord查询不返回结果时,如何防止控制器抛出错误 ActiveRecord::RecordNotFound in PasswordResetsController#edit Couldn't find User with password_reset_token = rqZEGQUH54390Pg-AUC5Q 我以为“!”符号会产生404,但至少在开发过程中,它会在浏览器中显示错误跟踪 如果查询不返回任何结果,下面的方法是否会在生产中生成404 如果没有,我如何修复 谢谢

当ActiveRecord查询不返回结果时,如何防止控制器抛出错误

 ActiveRecord::RecordNotFound in PasswordResetsController#edit
 Couldn't find User with password_reset_token = rqZEGQUH54390Pg-AUC5Q
我以为“!”符号会产生404,但至少在开发过程中,它会在浏览器中显示错误跟踪

如果查询不返回任何结果,下面的方法是否会在生产中生成404

如果没有,我如何修复

谢谢

    def edit
      @user = user.find_by_password_reset_token!(params[:id])
    end

使用
救援
条款:

def edit
  @user = user.find_by_password_reset_token!(params[:id])
rescue ActiveRecord::RecordNotFound => e
  # Do something with error, 'e'
end
或者使用控制器中的
rescue_from
(可在多个操作中重复使用:

rescue_from ActiveRecord::RecordNotFound, with: lambda do |e|
  # Do something with error, 'e'
end

def edit
  @user = user.find_by_password_reset_token!(params[:id])
end
在回答您的另一个问题时,它会在生产中显示HTTP 404错误,但不会显示堆栈跟踪。默认情况下,它会显示一个非常基本的错误页面,说明出现了问题。

请尝试:

 class PasswordResetsController
   def edit
     ...
     begin
      @user = user.find_by_password_reset_token!(params[:id])

     rescue ActiveRecord::RecordNotFound  
      redirect_to :controller => "{Your Controller}", :action => "{Your Action}"
      return
     end
    end
   end

没有问题。如果有帮助,你会考虑接受它吗?