简体   繁体   中英

How do I correctly handle redirects for bad url's to custom 404 page in ruby on rails?

Users can access others users profiles like this:

site.com/username

My find method in my users controller will find the user by their username.. now if the user doesn't exist I want them re-directed to a custom 404 error page I'll make.

I also want them re-directed for any other non-existant url's they type in.

I've found some solutions on google but wondering if someone can give me an up to date example of doing this in rails 3.2 as theses tutorials I've found are pre rails 3.1.

Kind regards

I tried this solution with Rails 3.2 and it just works.

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

  1. In your config/application.rb

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

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

     class ErrorsController < ApplicationController def not_found render status: 404 end def server_error render status: 500 end end 
  4. Create app/views/errors/not_found.html.haml and app/views/errors/server_error.html.haml (replace haml by erb if you do not use haml)

  5. Restart your server

在生产中, ActiveRecord::RecordNotFound异常将自动呈现您的public/404.html文件。

record is not found或输入invalid URL时,您始终可以呈现模板404以及状态代码

render :template => 'public/404.html', :status => 404

Here is the blog for "custom dynamic error pages in ruby on rails" will help you

custom dynamic error pages in ruby on rails

isnt it just in /public/404.html ?

UPDATE

Actually im pretty sure it is, that the same exact 404 page that comes up while running my page on nginx in production mode.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM