且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为生成的链接添加前缀,但不为传入路由添加前缀

更新时间:2023-12-01 10:23:40

此建议将使您能够轻松地为Rails路径助手生成的URL加上前缀。根据您的要求。请注意,但是,这也会使这些扩展路径对您的应用程序有效—它们应该仅在预期的位置进行路由,但是您会在 params 哈希中获得一些额外的值您可以忽略,所以我怀疑这是可以接受的。

This suggestion will allow you to easily prefix the urls produced by the Rails path helpers as your require. Do note, however, it will also make these extended paths valid requests for your application - they shoud just route where expected but you'll get get some extra values in the params hash that you can ignore, so I suspect this is possibly acceptable.

首先,将所有前缀位添加为可选参数您的路线的基本范围:

First, add all the prefix bits as optional parameters to your routes' base scope:

scope '(:portal/)(:prefixA/)(:prefixB)/myapp' do
  # routes
end

请注意,这些可选参数不能包含 / char,而不会被路径帮助程序转义,因此,如果前缀中有几个级别(在问题中似乎已经出现),则需要一些不同的设置参数,最后一个参数后跟一个斜杠,如上所述。

Note that the those optional params cannot include the / char without it being escaped by the path helpers, so if you have a few levels in the prefix (which it appears you do in the question) you'll need a few different params, all but the last followed by a slash, as above.

完成后,您应该在 ApplicationController $ c $中定义 default_url_options c>,它将返回您在路由中所需值的哈希值:

With that done, you should define default_url_options in your ApplicationController, it should return a hash of the values you need in your routes:

def default_url_options(_options={})
  {
    portal:  'portal',
    prefixA: 'whatevertheprefixis',
    prefixB: 'nextbitoftheprefix'
  }
end

这应该做,路径助手(以及 link_to @object 等),那么每次使用它们时都应包括这些值。

And that should do it, path helpers (along with link_to @object etc) should all now include those values every time you use them.

请注意,由于开始时 portal 位也是一个可选参数,您只需在 default_url_options 中添加其他逻辑,并在不希望出现这种前缀行为的情况下让它返回空哈希。

Note that since the portal bit at the start is also an optional parameter, you can simply add additional logic to default_url_options and have it return an empty hash whenever you do not want this prefixing behaviour.