开发者

How to use current subdomain in url helpers

I have a url helper from Devise as follows:

account_confirmation_url(@resource, :confirmation_tok开发者_如何学运维en => @resource.confirmation_token)

How do I make it create the url with the current subdomain instead of just the main subdomain?


The main solution described in the Devise wiki doesn’t work for setting arbitrary subdomains and is a problem if you’re triggering generation of email during a request in one subdomain (or the root domain of your application) and want the links in the email to reference a different subdomain.

The generally accepted way to make it work is to give the url_for helper a :subdomain option.

# app/helpers/subdomain_helper.rb

module SubdomainHelper
  def with_subdomain(subdomain)
    subdomain = (subdomain || "")
    subdomain += "." unless subdomain.empty?
    host = Rails.application.config.action_mailer.default_url_options[:host]
    [subdomain, host].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

The next step is crucial and I suspect it is where a lot of people get tripped up (I know I did). Make sure that Devise mixes your new subdomain helper into its mailer objects by adding the following code to config/application.rb

  config.to_prepare do
    Devise::Mailer.class_eval do 
      helper :subdomain 
    end
  end

Now when you do a link_to in your Devise mailer template, you can easily specify a :subdomain option.

link_to 'Click here to finish setting up your account on RightBonus',
  confirmation_url(@resource, :confirmation_token => @resource.confirmation_token, :subdomain => @resource.subdomain)


Try passing it :host => 'yoursub.domain.com'


You can look at Devise wiki: https://github.com/plataformatec/devise/wiki/How-To:-Send-emails-from-subdomains

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜