我能够 redirect使用 this line at the end of the routes file 的所有(无效)网址:
match '*a' => redirect('/')
我想进行重定向并在 routes.rb
中传递警告消息。
类似的东西(这里的语法是错误的):
match '*a' => redirect('/'), :alert => "aaargh, you don't want to go to #{params[:a]}"
这有可能吗?
如果我在 View / Controller 中执行此操作,我可以使用 redirect_to
并在重定向页面上传递一条闪现消息(参见 redirecting in the docs 中的示例)。创建一个新的 Controller 方法并在那里重定向是可行的,但它似乎不够优雅……这是推荐的方法吗?
最佳答案
对 Jun's answer 的轻微调整允许我这样做:
match '*a' => redirect { |p, req| req.flash[:error] = "aaargh, you don't want to go to #{p[:a]}"; '/' }
它将无效页面与所需的(动态)消息一起重定向到 '/'
。
如果您转到 www.your_website/a_bad_place
,这会在 '/'
上传递消息:
aaargh, you don't want to go to
a_bad_place
.
您可以使用以下方式获取整个违规(无效)网址:
#{req.env["HTTP_HOST"]}#{req.env["REQUEST_PATH"]}
并用这个显示它:
match '*a' => redirect { |p, req| req.flash[:error] = "aaargh, you don't want to go to #{req.env["HTTP_HOST"]}#{req.env["REQUEST_PATH"]}"; '/' }
你会看到:
aaargh, you don't want to go to
www.yourwebsite/a_bad_place
关于ruby-on-rails - 在路由中捕获所有内容时重定向并引发 flash 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16203961/