8

For example typing: localhost:3000/absurd-non-existing-route How do I get invalid routes to point to the main page of the application in Rails?

Jonathan
  • 10,936
  • 8
  • 64
  • 79
fenec
  • 5,637
  • 10
  • 56
  • 82

5 Answers5

6

On Rails 4+

Edit your routes.rb file by adding a get "*path", to: redirect('/') line just above the last end as mentioned by user @ Rails: redirect all unknown routes to root_url

Community
  • 1
  • 1
Epigene
  • 3,634
  • 1
  • 26
  • 31
6

The solution presented here works pretty well

#Last route in routes.rb
match '*a', :to => 'errors#routing'

# errors_controller.rb
class ErrorsController < ApplicationController
  def routing
    render_404
  end
end
Ryenski
  • 9,582
  • 3
  • 43
  • 47
3

Use rescue_from in your ApplicationController to rescue ActionController::RoutingError and redirect to the home page when it happens.

This will not work in Rails 3 currently. A ticket has been filed.

Jonathan
  • 10,936
  • 8
  • 64
  • 79
x1a4
  • 19,417
  • 5
  • 40
  • 40
1

If you are using rails 3,

Use the following solution

In your routes.rb, add the following line in the end of the file

match "*path" => "controller_name#action_name", via: [:get, :post]


And in your Controller, add

def action_name
  redirect_to root_path
end

If you are using rails 4

Write this line in your routes.rb

match '*path' => redirect('/'), via: :get
Nimish
  • 1,053
  • 13
  • 29
1

Here's something I came up with trying to find a universal catch-all solution for routing exceptions. It handles most popular content types.

routes.rb

get '*unmatched_route', to: 'errors#show', code: 404

ErrorsController

class ErrorsController < ApplicationController
  layout false

  # skipping CSRF protection is required here to be able to handle requests for js files
  skip_before_action :verify_authenticity_token

  respond_to :html, :js, :css, :json, :text

  def show
    respond_to do |format|
      format.html { render code.to_s, status: code }
      format.js   { head code }
      format.css  { head code }
      format.json { render json: Hash[error: code.to_s], status: code }
      format.text { render text: "Error: #{ code }", status: code }
    end
  end

  private

  def code
    params[:code]
  end
end

The ErrorsController is designed to be more universal, to handle all kind of errors.

It is advised to create your own view for the 404 error in app/views/errors/404.html.

Paweł Gościcki
  • 9,066
  • 5
  • 70
  • 81