Rails 4 ActionMailer Subdomain URL

When a rails 4 application is hosted on a subdomain, for example. sub.domain.com, how can you get the urls in the action mailer templates to correctly reference the subobject?

configurations / environment / production.rb:

config.action_mailer.default_url_options = { :host => 'sub.domain.com' }

Example action mailer template:

<%= user_url(@user) %>

In the email, the link appears as www.domain.com/users/1, rather thansub.domain.com/users/1

+4
source share
4 answers

This is actually easy. The best suggestion for solving this problem is that you create a before_filter file that sets it for each request in ApplicationController.rb as follows:

before_filter :set_mailer_host

  def set_mailer_host
    ActionMailer::Base.default_url_options[:host] = request.host_with_port
  end
+7
source

, , , - , .

default_url_options (, , ), URL-, .

<%= url_for() %>

, ( apidock):

url_for (options = nil) public URL- , default_url_options , route.rb. :

: only_path - true, URL-. false.

: protocol - . "http.

: host - , . : only_path , , default_url_options.

: subdomain - , tld_length . false, .

: domain - , tld_length .

: tld_length - , TLD, : : . ActionDispatch:: Http:: URL.tld_length, 1.

: port - .

: anchor - , .

: trailing_slash - true, , " //2009/"

: script_name - . , .

(: ,: ..), url_for, .

link_to "_url" . :

<%= link_to 'Yes', response_approvals_url(t: @secret_token) %>
+3

, . delayed_job https://github.com/collectiveidea/delayed_job . , script , , .

: RAILS_ENV=production bin/delayed_job restart

! , , .

0

For more information, click here http://railscasts.com/episodes/221-subdomains-in-rails-3 and here https://github.com/plataformatec/devise/wiki/How-To:-Send-emails -from-subdomains

 module UrlHelper
      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

    class ApplicationController < ActionController::Base
      include UrlHelper
    end 

Add the following code to app / helpers / url_helper.rb

def set_mailer_url_options
    ActionMailer::Base.default_url_options[:host] = with_subdomain(request.subdomain)
end

and modify the file app / controller / application_controller.rb to add:

before_filter :set_mailer_url_options
0
source

All Articles