ActionMailer 方法返回 nil

ActionMailer method returning nil

我为 Rails 应用程序创建了一个简单的票务系统。我现在需要在创建新工单时发送一封电子邮件。因此,我创建了以下 Mailer 类:

app/mailers/application_mailer.rb

class ApplicationMailer < ActionMailer::Base
  default to: Proc.new { "admin@domain" },
  from: 'admin@domain'

  def initialize(arg0, arg1)
    @base_url = 'http://app.domain'
  end

end

app/mailers/ticket_mailer.rb

class TicketMailer < ApplicationMailer

  def new_ticket(ticket)
    @ticket = ticket
    @url  = @base_url + '/tickets/' + @ticket.id.to_s
    mail(subject: "New Ticket: #{@ticket.title}")
  end
end

并修改了Ticket模型:

class Ticket < ActiveRecord::Base
  belongs_to :user
  belongs_to :ticket_status
  belongs_to :ticket_type

  has_many   :ticket_follow_ups

  after_create :send_ticket_mail

  def send_ticket_mail()
    TicketMailer.new_ticket(self).deliver
  end
end

当我尝试创建新工单时,我收到以下异常:

NoMethodError (undefined method deliver' for nil:NilClass):
app/models/ticket.rb:20:in
send_ticket_mail'
app/controllers/tickets_controller.rb:21:in `create'

我试过直接从控制器中调用方法,但结果是一样的。我错过了什么?

您可以试试

  def send_ticket_mail()
    TicketMailer.new.new_ticket(self).deliver
   end

基本上这个问题是由ApplicationMailerclass中的initialized方法引起的。如果将其删除并且 url 存储为常量:

,则事情会按预期运行
class ApplicationMailer < ActionMailer::Base
  default to: Proc.new { "admin@domain" },
  from: 'admin@domain'

  BASE_URL = 'http://app.domain'
end

当然,TicketMailer class 必须修改才能使用常量。