我知道我来晚了,但这个问题是谷歌搜索“在 routes.rb 中使用 url_helpers”时最热门的问题之一,我最初是在偶然发现这个问题时发现的,所以我会喜欢分享我的解决方案。
正如@martinjlowm 在他的回答中提到的那样,在绘制 新路线时不能使用 URL 助手。但是,有一种使用 URL 帮助程序定义重定向路由规则的方法。问题是,ActionDispatch::Routing::Redirection#redirect 可以接受一个块(或#call-able),这是稍后(当用户点击路线时)使用两个参数调用的,params 和 request,返回一个新的路由,一个字符串。并且由于此时路由已正确绘制,因此在块内调用 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