【问题标题】:Include subdomain for constrained route in Rails url helper在 Rails url 帮助器中包含受限路由的子域
【发布时间】:2012-05-09 02:10:37
【问题描述】:

假设我有以下受限于特定子域的路由:

App::Application.routes.draw do
  constraints :subdomain => "admin" do
    scope :module => "backend", :as => "backend" do
      resources :signups
      root :to => "signups#index"
    end
  end
  constraints :subdomain => "www" do
    resources :main
    root :to => "main#landing"
  end
end

我的问题是 root_urlbackend_root_url 都返回当前子域的 url:“http://current-subdomain.lvh.me/”而不是特定于资源。 我希望root_url 返回“http://www.lvh.me/”和backend_root_url 返回“http://admin.lvh.me /"(子域下所有资源的行为应该相同)。

我曾尝试在 rails 3.2 中通过在不同位置设置 url 选项来实现这一点,其中一个是应用程序控制器中的 url_options:

class ApplicationController < ActionController::Base
  def url_options
    {host: "lvh.me", only_path: false}.merge(super)
  end
end

也许我需要手动覆盖 url 助手?我将如何处理(访问路线等)?

编辑:我能够使用 root_url(:subdomain => "admin") 得到正确的结果,它返回 "http://admin.lvh.me/" 而不管当前子域。但是,我不希望在整个代码中都指定这一点。

【问题讨论】:

    标签: ruby-on-rails routes


    【解决方案1】:

    使用如下所示的“默认值”将使 rails url helpers 输出正确的子域。

    App::Application.routes.draw do
      constraints :subdomain => "admin" do
        scope :module => "backend", :as => "backend" do
          defaults :subdomain => "admin" do
            resources :signups
            root :to => "signups#index", :subdomain => "admin"
          end
        end
      end
    
      constraints :subdomain => "www" do
        defaults :subdomain => "www" do
          resources :main
          root :to => "main#landing"
        end
      end
    end
    

    【讨论】:

    • 这很好用!我遇到的一个问题是,这仅在您的基本域尚未包含子域时才有效。如果是这样,您需要将其包含为 :host。或者您可以通过定义 ApplicationController#default_url_options 来设置 :host 以返回包含 :host 的哈希。
    • 我收回它,如果您的主主机名已经有一个子域,即使这样也不能解决问题。如果不编写自己的辅助方法,我还没有想出办法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-15
    • 1970-01-01
    相关资源
    最近更新 更多