从Rails 2.3.x + gem subdomain_routes移植时,我遇到了有关Rails 3中子域的路由问题。使用subdomain_routes gem,我可以通过模型轻松映射路径,如下所示:
# config/routes.rb
map.subdomain :model => :site do |site|
resources :pages
end
这会生成网址助手,例如site_pages_url
,可以像这样使用:
# console
@site = Site.find_by_subdomain(“yehuda”)
app.site_pages_url(@site) => http://yehuda.example.com/pages
app.site_page_url(@site, @page) => http://yehuda.example.com/page/routes-rock
在Rails 3中,这大致会转化为:
# config/routes.rb
class SiteSubdomain
def self.matches?(request)
request.subdomain.present? && request.subdomain != 'www' &&
request.params[:site_id].present?
end
end
Blog::Application.routes.draw do
resources :sites do
constraints(SiteSubdomain) do
resources :pages
end
end
end
并且重载标准url_for应该基本上像在subdomain_routes中一样工作:
module UrlFor
def with_subdomain(subdomain)
subdomain = (subdomain || "")
subdomain += "." unless subdomain.empty?
[subdomain, request.domain, request.port_string].join
end
def url_for(options = nil)
if options.kind_of?(Hash) && options.has_key?(:subdomain)
options[:host] = with_subdomain(options.delete(:subdomain))
end
super
end
end
ActionDispatch::Routing::UrlFor.send(:include, UrlFor)
但是,网址助手仍然无法生成site_pages_url(@site) #=> http://www.example.com/pages
之类的正确网址,而不是预期的http://yehuda.example.com/pages
答案 0 :(得分:0)
您已将该课程命名为
SiteSubdomain
这实际上意味着,您的路由应该具有SiteSubdomain而不是Subdomain。修改为
Blog::Application.routes.draw do
resources :sites do
constraints(SiteSubdomain) do
resources :kases
end
end
end