新手问题 一套代码多个域名,怎么设置多个 root :to

Peter · 2015年01月15日 · 最后由 pynix 回复于 2015年01月22日 · 2960 次阅读

因为多个域名的网站结构相似,所以参考下面的文章集中在一套代码里实现了: http://www.nicolasgarnil.me/blog/2013/handling-multiple-domains-routes-in-ruby-on-rails/

so far so good, 开发测试都很愉快。

不过为每个域名指定不同的 index,也就是首页的时候,出现了问题

Rails.application.routes.draw do
  DomainsConstraintsExample::Application.routes.draw do

    constraints DomainConstraint.new(Rails.application.settings[:firstapp_domain]) do
      root to: "firstapp/firstapp#index"
      resources :firstapp, controller: "firstapp/firstapp"
    end

    constraints DomainConstraint.new(Rails.application.settings[:secondapp_domain]) do
      root to: "secondapp/secondapp#index"
      resources :secondapp, controller: "secondapp/secondapp"
    end
  end
  :
  :
end

也就是在不同的 constraints 使用了两个 root to:,结果报错:

Invalid route name, already in use: 'root' You may have defined two routes with the same name using the `:as` option, or you may be overriding a route already defined by a resource with the same naming. For the latter, you can restrict the routes created with `resources` as explained here:
http://guides.rubyonrails.org/routing.html#restricting-the-routes-created

google 无果,还望高手指点,谢谢!

namespace 就好了

root to 改为 match 试试?

Rails.application.routes.draw do
  DomainsConstraintsExample::Application.routes.draw do

    constraints DomainConstraint.new(Rails.application.settings[:firstapp_domain]) do
      match "/" => "firstapp/firstapp#index"
      resources :firstapp, controller: "firstapp/firstapp"
    end

    constraints DomainConstraint.new(Rails.application.settings[:secondapp_domain]) do
      match "/" => "secondapp/secondapp#index"
      resources :secondapp, controller: "secondapp/secondapp"
    end
  end
  :
  :
end

谢谢楼上各位 @neverlandxy_naix @george_d_y @Rei

已用 get "/" => 搞定,除了不能用 root_path,不知道还有什么其他影响。

@Rei 我这个是根目录,你那句 scope :module => 'site', :as => 'site' do 是不是加了一级 /site/ ? 看的文档:http://guides.rubyonrails.org/routing.html

Rails.application.routes.draw do
  DomainsConstraintsExample::Application.routes.draw do

    constraints DomainConstraint.new(Rails.application.settings[:firstapp_domain]) do
      get "/" =>  "firstapp/firstapp#index"
      resources :firstapp, controller: "firstapp/firstapp"
    end

    constraints DomainConstraint.new(Rails.application.settings[:secondapp_domain]) do
      get "/" => "secondapp/secondapp#index"
      resources :secondapp, controller: "secondapp/secondapp"
    end
  end
  :
  :
end

as: :root 不行吗?

需要 登录 后方可回复, 如果你还没有账号请 注册新账号