Ruby on Rails route for wildcard subdomains to a controller/action

前端 未结 2 2006
暗喜
暗喜 2021-02-08 14:13

I dynamically create URLs of the form username.users.example.com:

bob.users.example.com
tim.users.example.com
scott.users.example.com
相关标签:
2条回答
  • 2021-02-08 15:03

    I think, you just need to do the following :

    create a class Subdomain in lib :

      class Subdomain  
        def self.matches?(request)  
          request.subdomain.present? && request.host.include?('.users')
        end  
      end
    

    and in your routes :

    constraints Subdomain do
      match '', to: 'my_controller#show'
    end
    
    0 讨论(0)
  • 2021-02-08 15:06

    You can constraint route dynamically based on some specific criteria by creating a matches? method

    Lets say we have to filter sub domain of URL

    constraints Subdomain do
      get '*path', to: 'users#show'
    end
    
    class Subdomain
      def self.matches?(request)
        (request.subdomain.present? && request.subdomain.start_with?('.users')
      end
    end
    

    What we are doing here is checking for URL if it start with sub domain users then only hit users#show action. Your class must have mathes? method either class method or instance method. If you want to make it a instance method then do

    constraints Subdomain.new do
      get '*path', to: 'proxy#index'
    end
    

    you can achieve same thing using lambda as well like below.

    Instead of writing class we can also use lambdas

    get '*path', to: 'users#show', constraints: lambda{|request|request.env['SERVER_NAME'].match('.users')}
    
    0 讨论(0)
提交回复
热议问题