Rails redirecting invalid route to root
There are several possibilities. Here's one. You could add this to the bottom of your routes.rb:
match ':not_found' => 'my_controller#index',
:constraints => { :not_found => /.*/ }
which will establish a catch-all route to make MyController's index action handle any missing paths; it can detect them by looking at params[:not_found]
and doing whatever it wants, such as redirecting to the root_path (redirect_to root_url
), redirecting somewhere strategically based on the bad path, rendering something special, examining the referrer/referer for clues about the source, etc.The :constraints
option is necessary; otherwise the not_found
param won't be able to contain special characters like slashes and dots.
Put this at the bottom of your routes because, obviously, it will match everything, and you want to give your other routes first crack at the path.
If you only want to redirect, nothing more, you could do this instead (again, at the bottom):
match ':not_found' => redirect('/'), :constraints => { :not_found => /.*/ }
If No route match then redirect to root page
Make this statement the last in your config/routes.rb
file:
match "*path" => redirect("/")
The "*path"
will match anything and will redirect to the root path.For more info, take a look at route globbing and redirection in the official Rails guides.
Redirect All Routing Errors to Root URL of the Application
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.
Rails: redirect all unknown routes to root_url
If your project is powered by rails 3, add simply this line to your routes.rb
match '*path' => redirect('/')
Edit: If you're on Rails 4 or 5match '*path' => redirect('/'), via: :get
orget '*path' => redirect('/')
How to catch and redirect rails routes that are valid, but invalid resource id?
Check out rescue_from
. It's quite handy when you want to deviate from Rails' default behavior of displaying a 404 page.
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound, with: :record_not_found
private
def record_not_found
# handle redirect
end
end
Redirect to root url in Rails
You can handle this in the routes.rb.
we redirect the /home route to /. So if someone tries to access localhost:3000/home they will get automatically redirected to main page at localhost:3000.
get '/home' => redirect('/')
Rails: redirecting to wrong path
The problem was that "trips/index" is matched with "trips/:id" so automatically tracks me to "trips/show", because trips/id == trips/show. I add it manually so i had to delete these unnecessary routes, and it is ok. Thanks for tips.
Redirect PUT route to root_url automatically in routes.rb
I would personally handle this with your webserver software.
If you're using Apache, you could use something like:
#public/htaccess
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^*.txt$ http://example.com/ [R=301,L]
If you wanted to handle it in the Rails routes, you'd be able to use a redirect:
#config/routes.rb
unless Rails.env.development?
scope constraints: { format: 'txt' } do
match '*path', to: redirect('/'), via: [:get, :post, :put]
end
end
You'd have to make sure you are capturing only the routes you need to redirect, though.The problem you have with your setup is that it will capture every route you send to your app, and redirect to root
. In fact, this may end up causing an infinite recursion error.
My code above works only in production / staging (as yours).
It takes any .txt
route passed through the GET
, POST
or PUT
HTTP verbs, redirecting to the root path.
Ruby on Rails throws error wihen redirects to root_path or login_path
I think the code is not in create
method, and root_path is not a class method, is an instance method:
class SessionsController < ApplicationController
def new
end
def create
@user = User.find_by(username: params[:username])
@password = params[:password]
end # <--- here create method finish. Where this end comes from?
if @user && @user.authenticate(password)
session[:user_id] = @user.id
# root_path is defined for an instance
# of a controller, not for the class
redirect_to root_path, notice: "Logged in successfully"
else
redirect_to login_path, alert: "Invalid Username/Password combination"
end
def destroy
reset_session
redirect_to login_path, notice: "You have been logged out"
end
end
Related Topics
How to Test Helpers Blocks in Sinatra, Using Rspec
How to Have Two Columns in One Table Point to The Same Column in Another with Activerecord
Multistep Form with Activeadmin
How to Get Records Created at The Current Month
Why Are Global Methods Allowed to Be Defined Outside of a Class in Ruby
How to Specify Regexp Options Using Regexp.Union
Rails and JavaScript Minifier and Aggregator
Error Generating Source Map - Grunt and SASS Configuration
Ruby Dynamic Arguments in Dynamically Created Methods
How to Display Image Pointed by Url in Rails
Why Can't The Mail Block See My Variable
How to Validate Overlapping Times in Rails with Postgresql
Belongs_To Presence in Rails 5 Not Working
Should I Delete Migration After Rollback
Robust Way to Deploy a Rack Application (Sinatra)
How to Find Word with The Greatest Number of Repeated Letters