【问题标题】:Subdomain based resources in RailsRails 中基于子域的资源
【发布时间】:2014-10-02 12:38:12
【问题描述】:

我正在寻找一种简单的方法来用 Rails 4 将我所有匹配 mydomain.com/resources/xx 的路由替换为 xx.mydomain.com。

有没有人想轻松地做到这一点,并且也可以使用嵌套资源?

谢谢,乔里斯

【问题讨论】:

    标签: ruby-on-rails routes subdomain


    【解决方案1】:

    Constraints

    您正在寻找的是路由中的约束,特别是您希望使用一个来确定您是否有可以访问的子域

    有很多关于如何实现这一点的资源:

    底线是您可能必须创建一个自定义子域约束,然后您可以将标准路由结构用于:

    #lib/subdomain.rb
    class Subdomain
      def self.matches?(request)
        if request.subdomain.present? && request.subdomain != 'www'
            account = Account.find_by username: request.subdomain
            return true if account # -> if account is not found, return false (IE no route)
        end
      end
    end
    
    
    #config/routes.rb
    constraints(Subdomain) do
       get "/", to: "controller#action"
       resources :posts #-> subdomain.domain.com/posts
       ...
    end
    

    以上内容未经测试 - 我还通过Rails' documentation 找到了以下内容:

    #lib/subdomain.rb
    class Subdomain
      def initialize
        @accounts = Account.all
      end
    
      def matches?(request)
        if request.subdomain.present? && request.subdomain != 'www'
            @accounts.include?(request.subdomain)
        end
      end
    end
    
    #config/routes.rb
    constraints: Subdomain.new do
       get "/", to: "controller#action"
       resources :posts #-> subdomain.domain.com/posts
       ...
    end
    

    【讨论】:

    • 好的,谢谢。但是没有办法将子域自动绑定到一个参数,无论是在控制器 params[:account_id] 中检索它(就像我现在所做的那样),还是创建新的路径或 url,其 id 将设置为子域? (account_path(@account) 将返回 account_slug.domain.com 或 account_id.domain.com)。那很好,但我想我必须更改控制器中的视图和变量中的所有路由。
    【解决方案2】:

    这是我之前在 Rails 3 应用程序中的做法:

      constraints :subdomain => /ambassador/ do
        namespace(:influencer, :path => '/') do
          root :to => 'home#index'
          match 'home' => 'sweepstakes#index', :as => :influencer_home
          resources :sweepstakes
          resources :associates
          resources :widgets
          resources :sessions
          resources :reports do
            resource :member
          end
          match 'faq' => 'info#faq'
        end
      end
    

    请务必将此块放在 routes.rb 文件的顶部,以便优先。

    你当然可以像往常一样在这里嵌套你的资源。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-20
      • 1970-01-01
      • 1970-01-01
      • 2019-06-28
      • 1970-01-01
      • 2017-09-13
      • 1970-01-01
      相关资源
      最近更新 更多