如何正确处理重定向错误的网址到ruby on rails上的自定义404页面?

时间:2012-02-24 23:35:45

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1 rubygems

用户可以访问其他用户个人资料,如下所示:

site.com/username

我的用户控制器中的查找方法将通过用户名找到用户..现在,如果用户不存在,我希望将它们重定向到我将要制作的自定义404错误页面。

我还希望他们重新定向他们输入的任何其他不存在的网址。

我在google上找到了一些解决方案但是想知道是否有人可以在rails 3.2中给我一个最新的例子,因为我发现这些教程是pre rails 3.1。

亲切的问候

5 个答案:

答案 0 :(得分:6)

我使用Rails 3.2尝试了这个解决方案,它只是有效。

https://makandracards.com/makandra/12807-custom-error-pages-in-rails-3-2

  1. config/application.rb

    config.exceptions_app = self.routes
    
  2. config/routes.rb

    get '/404', to: 'errors#not_found'
    get '/500', to: 'errors#server_error'
    
  3. 创建app/controllers/errors_controller.rb

    class ErrorsController < ApplicationController
      def not_found
        render status: 404
      end
    
      def server_error
        render status: 500
      end
    end
    
  4. 创建app/views/errors/not_found.html.hamlapp/views/errors/server_error.html.haml(如果您不使用haml,请将haml替换为erb

  5. 重新启动服务器

答案 1 :(得分:0)

在制作中,ActiveRecord::RecordNotFound例外会自动呈现您的public/404.html文件。

答案 2 :(得分:0)

在输入record is not foundinvalid URL

时,您始终可以将模板404与状态代码一起呈现
render :template => 'public/404.html', :status => 404

答案 3 :(得分:0)

以下是“ruby on rails中的自定义动态错误页面”的博客将帮助您

custom dynamic error pages in ruby on rails

答案 4 :(得分:-1)

不在/public/404.html吗?

更新

实际上我很确定它是在生产模式下在nginx上运行我的页面时出现的完全相同的404页面。