【发布时间】:2014-10-02 12:38:12
【问题描述】:
我正在寻找一种简单的方法来用 Rails 4 将我所有匹配 mydomain.com/resources/xx 的路由替换为 xx.mydomain.com。
有没有人想轻松地做到这一点,并且也可以使用嵌套资源?
谢谢,乔里斯
【问题讨论】:
标签: ruby-on-rails routes subdomain
我正在寻找一种简单的方法来用 Rails 4 将我所有匹配 mydomain.com/resources/xx 的路由替换为 xx.mydomain.com。
有没有人想轻松地做到这一点,并且也可以使用嵌套资源?
谢谢,乔里斯
【问题讨论】:
标签: ruby-on-rails routes subdomain
您正在寻找的是路由中的约束,特别是您希望使用一个来确定您是否有可以访问的子域
有很多关于如何实现这一点的资源:
底线是您可能必须创建一个自定义子域约束,然后您可以将标准路由结构用于:
#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
【讨论】:
这是我之前在 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 文件的顶部,以便优先。
你当然可以像往常一样在这里嵌套你的资源。
【讨论】: