编辑:弄清楚了,布局遵循与电子邮件模板不同的命名方案。只需将它们重命名如下:
layout.text.html.erb => layout.html.erb
layout.text.plain.erb => layout.text.erb
如果您使用以下命令,我还犯了手动定义零件的错误:
part :content_type => 'text/plain',
:body => render_message('my_template')
然后 Rails 无法确定您的部分的 content_type 并且它假定它是 HTML。
在我改变了这两件事之后,它对我有用!
原回复如下..
过去我曾多次为这个问题苦苦挣扎,通常最终都会得到某种不干的快速而肮脏的解决方案。我一直以为我是唯一遇到这个问题的人,因为谷歌在这个问题上没有发现任何有用的东西。
这次我决定深入研究 Rails 来解决这个问题,但到目前为止还没有取得多大成功,但也许我的发现会帮助其他人解决这个问题。
我发现在 ActionMailer::Base 中,#render_message 方法的任务是确定正确的 content_type,并应将其分配给 @current_template_content_type。 #default_template_format 然后返回布局的正确 mime 类型,或者如果未设置 @current_template_content_type,则默认为 :html。
这就是 ActionMailer::Base#render_message 在我的应用程序中的样子 (2.3.5)
def render_message(method_name, body)
if method_name.respond_to?(:content_type)
@current_template_content_type = method_name.content_type
end
render :file => method_name, :body => body
ensure
@current_template_content_type = nil
end
问题在于 method_name 似乎是一个字符串(本地视图的名称,在我的例子中为“new_password.text.html”),并且字符串当然不会响应 #content_type,这意味着 @current_template_content_type 将始终保持为零,因此#default_template_format 将始终默认为 :html。
我知道,离实际的解决方案还差得远。 ActionMailer 的内部结构对我来说太不透明了。