Rails ActionView::MissingTemplate,邮件程序缺少模板

Rails ActionView::MissingTemplate, Template Is Missing for mailer

提问人:Misha Krul 提问时间:8/11/2023 更新时间:8/11/2023 访问量:37

问:

我有一个名为 ContactUsMailer 的邮件类,它继承自 ActionMailer::Base。

class ContactUsMailer < ActionMailer::Base
  default from: '[email protected]'

  def contact_us(name:, email:, message:)
    @name = name
    @email = email
    @message = message
    mail(
      to: '[email protected]',
      subject: "New email inquiry from #{@name} (#{@email})",
      template_path: 'views/mailers/contact_us_mailer',
      template_name: 'contact_us'
    )
  end
end

它是从 ContactUsController 调用的。

class ContactUsController < ApplicationController

  def index
  end

  def create
    if params[:name].blank? || params[:email].blank? || params[:message].blank?
      flash[:error] = "Your name, email, and a message are required. Please try again."
    else
      ContactUsMailer.contact_us(
        name: params[:name],
        email: params[:email],
        message: params[:message]
      ).deliver!

      flash[:notice] = "Thank you for contacting us. We will get back to you shortly."
    end

    redirect_to contact_us_path
  end

  private

end

我的邮件模板位于 views/mailers/contact_us_mailer 下。

<!DOCTYPE html>
<html>
  <head>
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
  </head>
  <body>
    <p>
      New inquiry from <%= @name %>
    </p>
    <p>
      Email: <%= @email %>
    </p>
    ---------
    Message: <%= @message %>
  </body>
</html>

如果我不添加到调用中,我会收到以下错误:body:mail()ContactUsMailer


Template is missing
Missing template views/mailers/contact_us_mailer/contact_us with "mailer". Searched in: * "views/mailers/contact_us_mailer" 

如果我确实添加到呼叫中,我不会收到任何错误,并且电子邮件已成功发送,但是电子邮件仅包含消息,而不包含模板本身。body: @messagemail()

我不明白为什么 Rails 无法识别模板,即使我指定了路径。深入研究该方法,它可以清楚地识别标头中的模板数据。collect_responses_from_templates(headers)

def collect_responses_from_templates(headers)
=> 986:         templates_path = headers[:template_path] || self.class.mailer_name
   987:         templates_name = headers[:template_name] || action_name
   988: 
   989:         each_template(Array(templates_path), templates_name).map do |template|
   990:           format = template.format || self.formats.first
(byebug) headers[:template_path]
"views/mailers/contact_us_mailer"

关于如何进行的任何建议将不胜感激。

Ruby-on-Rails 模板 ActionMailer Mailer

评论

0赞 Andres Salazar Lopez 8/11/2023
尝试以这种格式执行此操作,应该以动态方式获取模板,而不是在邮件中设置配置。mail( to: '[email protected]', subject: "New email inquiry from #{@name} (#{@email})") do |format| format.mjml format.text end
0赞 Misha Krul 8/11/2023
我已经这样做了,不幸的是,我仍然收到缺少模板的错误。Missing template contact_us_mailer/contact_us
0赞 dbugger 8/11/2023
您的视图文件名是什么?
0赞 Misha Krul 8/11/2023
想通了。我在下面发布了解决方案。

答:

1赞 Misha Krul 8/11/2023 #1

想通了。

我尝试通过重新生成邮件程序,并注意到它在 ..我原来的邮件位于 .拥有命名空间路径一定是抛弃了 Rails 的魔力。bundle exec rails generate mailer contact_usapp/mailers/contact_us_mailer.rbapp/mailers/contact_us_mailer/