如何将 ActionMailer default_url_options 的 :host 动态设置为请求的主机名? [英] How to set the ActionMailer default_url_options's :host dynamically to the request's hostname?
问题描述
我正在尝试设置 :host for action mailer 默认 url 选项.
I am trying to set the :host for action mailer default url options.
我在所有环境文件中都设置了以下内容
I have the below set in all the environment files
config.action_mailer.default_url_options = {
:host => "localhost"
}
我想通过提供请求主机使其更具动态性.
I want to make it more dynamic by providing the request host.
当我尝试通过
config.action_mailer.default_url_options = {
:host => request.domain
}
或
config.action_mailer.default_url_options = {
:host => request.env["SERVER_NAME"]
}
它抛出错误...无法识别请求"对象
It throws error... doesn't recognize "request" object
有什么方法可以将其设置为请求主机,而不是通过硬编码...?
is there any way I can set this to the request host, not by hardcoding...?
推荐答案
还可以通过在 default_url_options 哈希中设置 :host 选项来设置将在所有邮件程序中使用的默认主机
It is also possible to set a default host that will be used in all mailers by setting the :host option in the default_url_options hash
在 application_controller.rb
中添加:
class ApplicationController < ActionController::Base
def default_url_options
{ host: request.host_with_port }
end
end
来源:https://edgeguides.rubyonrails.org/action_controller_overview.html#默认网址选项
或者,您可以在从控制器调用邮件程序函数时传递request
Alternatively, you can pass the request
when calling the mailer function from the controller
class UserMailer < ActionMailer::Base
def welcome_email(user, request)
@user = user
@url = user_url(@user, host: request.host_with_port ) # do this for each link
mail(:to => user.email, :subject => "Welcome to My Awesome Site")
end
end
来源:https://guides.rubyonrails.org/action_mailer_basics.html#generating-urls-with-named-routes
这篇关于如何将 ActionMailer default_url_options 的 :host 动态设置为请求的主机名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!