Rails 3.1 load controller from different path based on subdomain

只谈情不闲聊 提交于 2019-12-11 14:24:42

问题


Is it possible to dynamically change the path from which controllers are used? Ryan Bates showed how to change the view_paths here: http://railscasts.com/episodes/269-template-inheritance

I'm making a CMS where a user can create a site and enter their own subdomain. I'd like "/" to point to "public#welcome" if there's no subdomain, but if there is a subdomain, I want it to point to "sites/public#welcome".

I'm using Rails 3.1 if that makes any difference.


回答1:


You should be able to solve this situation using constraints if I'm not mistaken (which I might, since I haven't actually tried the following yet):

constraints(:subdomain => /.+/) do
  root :to => 'sites/public#welcome'
end

root :to => 'public#welcome'



回答2:


I figured it out:

  constraints(:subdomain => /.+/) do
    scope :module => "sites" do
      root :to => 'public#welcome'
    end
  end

  root :to => 'public#welcome'

Now when a user visits "/" Sites::PublicController will be used if a subdomain exists, but just PublicController if no subdomain exits. Adding scope :module => "sites" do...end keeps my routes file simplistic and manageable.



来源:https://stackoverflow.com/questions/6442919/rails-3-1-load-controller-from-different-path-based-on-subdomain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!