【问题标题】:Rails Subdomain in Host Being Replaced主机中的 Rails 子域被替换
【发布时间】:2016-10-27 20:21:48
【问题描述】:

鉴于以下config/routes.rb

constraints subdomain: 'subdomain' do
  get 'path', to: 'main#index', as: :sample
end

以下作品:

Rails.application.routes.url_helpers.sample_url(host: "a.b")
# "http://subdomain.a.b/path"

以下失败:

Rails.application.routes.url_helpers.sample_url(host: "a.b.c")
# "http://subdomain.b.c/path"

有什么方法可以修复它,这样子域就不会替换主机中现有的子域,而是链接起来(即http://subdomain.a.b.c/path)?我意识到我可以将路由中的子域更改为 subdomain.a - 但是维护多个子域/部署会有点痛苦。

【问题讨论】:

  • 请注意,如果您正在调用子域,则可以使用 _url 助手而不是 _path。 EG sample_url(:args) -- 将节省调用 Rails.application.routes...
  • @RichardPeck 是的 - 但如果您从控制台调用,则需要前缀 Rails.application.routes.url_helpers。请注意,该示例使用 _url 助手。
  • 是的,当然,我没有意识到你是从 cmd 执行的。

标签: ruby-on-rails ruby


【解决方案1】:

看来你需要检查tld_length

:tld_length - TLD id 组成的标签数量,仅在以下情况下使用 提供:subdomain:domain。默认为 ActionDispatch::Http::URL.tld_length,默认为 1。

我将测试细节,但问题看起来像 Rails 只允许 tld(顶级域)长度为 1,这意味着您只能拥有一个子域和 1 个“其他”元素(@987654328 @/subdomain.a.b)。

修复应该是扩展tld_length,根据this answer,可以在配置设置/config/application.rb中完成:

# config/application.rb
config.action_dispatch.tld_length = 2

测试

没有tld_length

c:\Dev\Apps\torches>rails c
Loading development environment (Rails 5.0.0.1)
irb(main):001:0> Rails.application.routes.url_helpers.sample_url(host: "a.b")
=> "http://subdomain.a.b/path"
irb(main):002:0> Rails.application.routes.url_helpers.sample_url(host: "a.b.c")
=> "http://subdomain.b.c/path"
irb(main):003:0>

tld_length:

c:\Dev\Apps\torches>rails c
Loading development environment (Rails 5.0.0.1)
irb(main):001:0> Rails.application.routes.url_helpers.sample_url(host: "a.b")
=> "http://subdomain.a.b/path"
irb(main):002:0> Rails.application.routes.url_helpers.sample_url(host: "a.b.c")
=> "http://subdomain.a.b.c/path"
irb(main):003:0>

【讨论】:

  • 谢谢!正是我想要的!
【解决方案2】:

创建 config/initializers/host_name.rb 文件,您可以在其中放置一个常量:

HOST_NAME = 'b.c'

然后在你的代码中的任何地方:

Rails.application.routes.url_helpers.sample_url(host: HOST_NAME, subdomain: 'subdomain.a')

如果您愿意,您还可以为您的子域创建常量

【讨论】:

    猜你喜欢
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2016-03-21
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    相关资源
    最近更新 更多