在routes.rb中访问URL帮助程序

我想使用以下行重定向路径中的路径:

get 'privacy_policy', :controller => :pages, :as => 'privacy_policy' get 'privacypolicy.php' => redirect(privacy_policy_url) 

这样/privacypolicy.php就会被重定向到正上方定义的正确页面。

但是,它抛出以下错误:

 undefined local variable or method `privacy_policy_url' 

所以我猜测不能在routes.rb中使用URL助手。 有没有办法在路由文件中使用URL帮助程序,是否可以这样做?

我知道我在这里有点晚了,但这个问题是谷歌搜索“在routes.rb中使用url_helpers”时最热门的一个问题,我最初在遇到这个问题时发现了它,所以我想分享一下我的解决方案

正如@martinjlowm在他的回答中提到的,在绘制新路线时不能使用URL助手。 但是,有一种方法可以使用URL帮助程序定义重定向路由规则。 问题是, ActionDispatch :: Routing :: Redirection #call可以使用一个块(或一个#call -able),后者(当用户点击路径时)调用两个参数paramsrequest ,以返回一个新的路线,一个字符串。 并且因为在那一刻正确绘制了路径,所以在块内调用URL帮助器是完全有效的!

 get 'privacypolicy.php', to: redirect { |_params, _request| Rails.application.routes.url_helpers.privacy_policy_path } 

此外,我们可以使用Ruby元编程工具来添加一些糖:

 class UrlHelpersRedirector def self.method_missing(method, *args, **kwargs) # rubocop:disable Style/MethodMissing new(method, args, kwargs) end def initialize(url_helper, args, kwargs) @url_helper = url_helper @args = args @kwargs = kwargs end def call(_params, _request) url_helpers.public_send(@url_helper, *@args, **@kwargs) end private def url_helpers Rails.application.routes.url_helpers end end # ... Rails.application.routes.draw do get 'privacypolicy.php', to: redirect(UrlHelperRedirector.privacy_policy_path) end 

URL助手是从路径创建的。 因此,在绘制新路线时它们将无法使用。

你将不得不使用gayavat的方法。

– 要么 –

使用像http://guides.rubyonrails.org/routing.html这样的确切url重定向。

编辑:

如果它不仅仅是一个’… php’路线,你可能想要考虑制作一个重定向控制器。 看看这里,如何提升它: http : //palexander.posterous.com/provide-valid-301-redirects-using-rails-route

在您的路线文件中,您应该在底部添加它,因此它不会干扰其他路线:

 get '/:url' => 'redirect#index' 

就像是:

 get 'privacypolicy.php' => "privacy_policy#show"