【问题标题】:Redirect and raise flash message when catch-all in routes路由中的全部内容时重定向并引发闪烁消息
【发布时间】:2013-04-18 17:03:29
【问题描述】:

我可以使用this line at the end of the routes fileredirect所有(无效)网址:

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

我想进行重定向并在routes.rb 中传递警报消息。
类似的东西(这里的语法错误):

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

可以这样做吗?

如果我在视图/控制器中执行此操作,我可以使用 redirect_to 并在重定向页面上传递一条 flash 消息(参见 redirecting in the docs 中的示例)。创建一个新的控制器方法并在那里重定向可以工作,但它似乎不优雅......这是推荐的方式吗?

【问题讨论】:

    标签: ruby-on-rails routes


    【解决方案1】:

    我能做的最好的就是:

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

    【讨论】:

    • 谢谢!我能够进行一些细微的修改,这让我朝着正确的方向前进:)
    【解决方案2】:

    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,你不想去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,你不想去www.yourwebsite/a_bad_place

    【讨论】:

      猜你喜欢
      • 2011-09-05
      • 2021-11-09
      • 2022-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-24
      • 1970-01-01
      • 2013-08-17
      相关资源
      最近更新 更多