2014-01-06 32 views
2

我正在将Rails 3应用程序迁移到Rails 4.对于我们的应用程序,我们有两个顶级域用于我们的英文网站和日文网站。要动态链接到相应的网站,我们正在扩展url_for,如下所示用Rails连接到url_for 4

module I18nWwwUrlFor 
    def url_for(options=nil) 
    if options.kind_of?(Hash) && !options[:only_path] 
     if %r{^/?www} =~ options[:controller] 
     options[:host] = i18n_host 
     end 
    end 
    super 
    end 
end 

OurApplication::Application.routes.extend I18nWwwUrlFor 

在Rails 4下,这不起作用。这是因为命名路由现在直接调用ActionDispatch :: Http :: URL.url_for,它会接受选项并生成一个URL。理想情况下,我想扩展这个url_for,但没有任何挂钩,所以我留下了用alias_method_chain修补猴子。我错过了什么,有没有更好的方式来做到这一点?

回答

1

我用于与子域名的Rails应用程序4如下:

module UrlHelper 
    def url_for(options = nil) 
    if options.is_a?(Hash) && options.has_key?(:subdomain) 
     options[:host] = host_with options.delete(:subdomain) 
    end 
    super 
    end 

    def host_with(subdomain) 
    subdomain += '.' unless subdomain.blank? 
    [ subdomain, request.domain, request.port_string ].join 
    end 
end 

确保正确包括帮手application_controller.rb,否则将无法在两个控制器和视图的工作。

include UrlHelper 
helper UrlHelper 

指定要修改的子域名。

root_path(subdomain: 'ja') 
+0

嗯,只有_path助手调用url_for。我们正在使用_url,它不再通过url_for。所以root_path会像你显示的那样工作,但是root_url不会。 –

+0

你使用'_url'方法的任何原因? – AJcodez

+0

因为通常在需要完整URL时使用_url,而_path是针对相对路径。 –