Redirect and raise flash message when catch-all in

2019-07-06 05:21发布

问题:

I am able to redirect all (invalid) urls using this line at the end of the routes file:

match '*a' => redirect('/') 

I'd like to do the redirect and pass on an alert message in routes.rb.
Something like (the syntax is wrong here):

match '*a' => redirect('/'), :alert => "aaargh, you don't want to go to #{params[:a]}"

Is it possible to do this?

If I were doing this in a view/controller, I could use redirect_to and pass on a flash message on the redirected page (see examples in redirecting in the docs). Creating a new controller method and redirecting there would work, but it seems inelegant... is it the recommended way?

回答1:

A slight tweaking of Jun's answer allowed me to do this:

match '*a' => redirect { |p, req| req.flash[:error] = "aaargh, you don't want to go to #{p[:a]}"; '/' }

Which redirects invalid pages to '/' along with the desired (dynamic) message.

If you go to www.your_website/a_bad_place this passes the message on '/':

aaargh, you don't want to go to a_bad_place

.

You can grab the entire offending (invalid) url by using:

#{req.env["HTTP_HOST"]}#{req.env["REQUEST_PATH"]}

and display it with this:

match '*a' => redirect { |p, req| req.flash[:error] = "aaargh, you don't want to go to #{req.env["HTTP_HOST"]}#{req.env["REQUEST_PATH"]}"; '/' }

and you'll see:

aaargh, you don't want to go to www.yourwebsite/a_bad_place



回答2:

The best I can do is:

match 'PATH' => redirect { |p, req| req.flash[:alert] = "MESSAGE"; '/' }