Ruby on rails 在actionmailer中,如何在运行时覆盖默认的url选项?

Ruby on rails 在actionmailer中,如何在运行时覆盖默认的url选项?,ruby-on-rails,actionmailer,Ruby On Rails,Actionmailer,我需要能够生成链接的网站,所有运行我的应用程序,但有不同的域(我运行一个白标签服务) 代表这些域发送的电子邮件将根据邮件设置不同的主机 通常我会设置主机值应用程序。rb: config.action_mailer.default_url_options[:host] = 'myhost.com' Rails.configuration.action_mailer.default_url_options[:host] = new_host mail(...) 但是,由于我的主机根据链接的不同而

我需要能够生成链接的网站,所有运行我的应用程序,但有不同的域(我运行一个白标签服务)

代表这些域发送的电子邮件将根据邮件设置不同的主机

通常我会设置
主机
应用程序。rb

config.action_mailer.default_url_options[:host] = 'myhost.com'
Rails.configuration.action_mailer.default_url_options[:host] = new_host
mail(...)
但是,由于我的主机根据链接的不同而不同,因此我尝试在运行时执行此操作

用户\u mailer.rb

config.action_mailer.default_url_options[:host] = 'myhost.com'
Rails.configuration.action_mailer.default_url_options[:host] = new_host
mail(...)

问题是每次我运行它时,它都会继续使用
application.rb
中定义的内容。我似乎无法让应用程序尊重新定义的
default\u url\u选项[:host]
的值。我做错了什么?

如果没有太多的视图,您只需在url\u上为helper定义主机,如果有太多的视图,我建议您编写自己的帮助程序,用
:host=>'mysite.com'

包装帮助程序的url\u,如果没有太多视图,您可以简单地在帮助程序的url\u上定义主机,如果有太多的视图,我建议您编写自己的帮助程序,用
:host=>'mysite.com'

包装帮助程序的url\u,默认的\u url\u选项方法是在ActionMailer上使用class\u属性设置的,该属性在ActiveSupport core extensions for class中定义。根据文档,它还提供了一个实例级访问器,可以在不影响类级方法的情况下对每个实例进行重写。因此,您应该能够直接覆盖每封电子邮件的主机设置

class UserMailer < ActionMailer::Base
  def welcome(user)
    @user = user

    # don't need this if you override #mail method.
    self.default_url_options = default_url_options.merge(host: @user.host)

    mail(to: user.email, subject: "Welcome")
  end

  # might be better to override mail method if you need it for all emails in
  # a particular mailer
  private

  def mail(headers, &block)
    self.default_url_options = default_url_options.merge(host: @user.host)

    super
  end
end
class UserMailer

这应该允许您在运行时修改设置;请忽略@user.host调用,并将其替换为您将确定主机的方式。

默认的\u url\u选项方法是使用类的ActiveSupport core extensions中定义的类属性在ActionMailer上设置的。根据文档,它还提供了一个实例级访问器,可以在不影响类级方法的情况下对每个实例进行重写。因此,您应该能够直接覆盖每封电子邮件的主机设置

class UserMailer < ActionMailer::Base
  def welcome(user)
    @user = user

    # don't need this if you override #mail method.
    self.default_url_options = default_url_options.merge(host: @user.host)

    mail(to: user.email, subject: "Welcome")
  end

  # might be better to override mail method if you need it for all emails in
  # a particular mailer
  private

  def mail(headers, &block)
    self.default_url_options = default_url_options.merge(host: @user.host)

    super
  end
end
class UserMailer

这应该允许您在运行时修改设置;请忽略@user.host呼叫,并将其替换为您确定的主机。

谢谢。您知道是否可以强制主机使用实际路径帮助程序,例如
新用户\u url主机:'testhost.com'
?谢谢。您知道是否可以强制主机使用实际路径帮助程序,例如
new\u user\u url主机:“testhost.com”