路由全包时重定向并引发Flash消息 [英] Redirect and raise flash message when catch-all in routes
问题描述
我能够重定向使用在路由文件末尾的这一行:
match'* a'=> redirect('/')
我想进行重定向并在其中传递警报消息 routes.rb
。
有点像(这里的语法错误):
match'* a'=> redirect(’/’),:alert => aaargh,您不想去#{params [:a]}
是
如果在视图/控制器中执行此操作,则可以使用 redirect_to
并在重定向页面上传递Flash消息(请参阅文档中重定向中的示例)。创建一个新的控制器方法并重定向到那里可以用,但是似乎不太好...这是推荐的方法吗?
对 Jun的答案进行了细微调整使我可以这样做:
match'* a'=>重定向{| p,req | req.flash [:error] = aaargh,您不想转到#{p [:a]}; '/'}
将无效页面重定向到'/'
以及所需的(动态)消息。
如果您访问 www.your_website / a_bad_place
会在'/'
上传递消息:
aaargh,您不想转到
a_bad_place
。 / p>
您可以使用以下方法获取整个违规(无效)网址:
#{req.env [ HTTP_HOST]}#{req.env [ REQUEST_PATH]}
并显示以下内容:
match'* a'=>重定向{| p,req | req.flash [:error] = aaargh,您不想转到#{req.env [ HTTP_HOST]}#{req.env [ REQUEST_PATH]}}; '/'}
,您会看到:
aaargh,您不想访问
www.yourwebsite / a_bad_place
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?
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
这篇关于路由全包时重定向并引发Flash消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!