【问题标题】:Rails 3 routes redirect to named url without hitting controllerRails 3 路由重定向到命名 url 而无需点击控制器
【发布时间】:2012-10-21 01:39:25
【问题描述】:

根据Rails Routing Redirection guide,似乎没有一种简单的方法可以将匹配的 URL 重定向到路由文件中的另一个命名 URL。

我希望我可以在我的 routes.rb 中进行这样或类似的重定向,而无需在重定向函数中指定完整的 url 路径 ("/articles/%{id}")。

match "articles/:id" => "articles#show", :as=>'article'
match "articles/view/:id", :to => redirect(article_path) 

是否有插件或 gem 可以提供此功能?


我的最终解决方案包括根据接受的答案添加如下函数。

# handles redirecting a matched URL to a named URL
# source_match = string to match against
# dest_name = symbol of the named URL 
def redirect_to_url(source_match,dest_name)
    param_symbols = source_match.scan(/:([a-z\-\_]+)/i).flatten.map{|i| i.to_sym}
    match source_match, :to=>redirect{|params,request| 
        Rails.application.routes.url_helpers.send("#{dest_name}_path", params.slice(*param_symbols))
    }
end

【问题讨论】:

    标签: ruby-on-rails-3 redirect routes


    【解决方案1】:

    这是可以实现的,您只需通过重定向的 lambda 版本直接引用 Rails URL 帮助模块,因为您需要延迟解决:

    match "articles/view/:id", redirect {Rails.application.routes.url_helpers.article_path}
    

    请注意,这可能不起作用,因为 article_path 需要传递一个 id 才能运行。 如果是这种情况,您可以使用传递给重定向指令的 lambda 版本的参数:

    match "articles/view/:id", redirect {|params, request| Rails.application.routes.url_helpers.article_path(params[:id]) }
    

    【讨论】:

      猜你喜欢
      • 2012-03-07
      • 1970-01-01
      • 2011-07-07
      • 1970-01-01
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多