Rails动作邮件如果声明

时间:2013-09-21 16:59:13

标签: ruby-on-rails ruby-on-rails-3 actionmailer

我正在尝试将一些逻辑放入我的邮件程序中。基本上,我在我的一个模型中有十几个布尔字段,对于每个真实的字段,我希望将电子邮件发送到特定地址。具有布尔字段的模型称为Ecn。这是我的通知文件:

class EcnNotifier < ActionMailer::Base
  default from: "engineering_notices@wilfley.com"

  def submitted(ecn)
    @ecn = ecn
    @email_list = EmailList.all
    if @ecn.distribute_engineering?  
        mail to: "abc@gmail.com", subject: 'ECN approvald' 
    else

    end
    if @ecn.distribute_purchasing? 
        mail to: "123@gmail.com", subject: 'ECN approval' 
    else

    end
    mail to: "aaa@test.com", subject: 'ECN approval'
  end
end

我在控制器中创建的动作如下所示:

  def submit

    @ecn = Ecn.find(params[:id])

    respond_to do |format|
      EcnNotifier.submitted(@ecn).deliver
      format.html { redirect_to ecns_url, alert: "Ecn has been submitted for approval." }
      format.json { render json: @ecns }
    end
  end

电子邮件会自动发送到aaa@test.com,但无论distribute_engineering和distribute_purchasing是否为true,都不会向其他地址发送电子邮件。我假设我错误地访问了我的对象实例,但我不确定我哪里出错了。

2 个答案:

答案 0 :(得分:1)

您只能通过一次deliver来电发送一封邮件。您必须将您的逻辑移到邮件程序之外,或使用cc或bcc将邮件传递给多个收件人。

答案 1 :(得分:1)

我认为你只能在一个邮件程序中发送一封邮件,而不是多封邮件。您可以发送一封邮件并添加几个cc或密件抄送,但只能在一个操作范围内发送一封邮件。

我会将控制器更改为以下内容:

def submit
  @ecn = Ecn.find(params[:id])

  respond_to do |format|
    EcnNotifier.notify_default(@ecn).deliver
    EcnNotifier.distribute_engineering(@ecn).delifer if @ecn.distribute_engineering?
    EcnNotifier.distribute_purchasing(@ecn).deliver if @ecn.distribute_purchasing?
    # and so on...
    format.html { redirect_to ecns_url, alert: "Ecn has been submitted for approval." }
    format.json { render json: @ecns }
  end
end

你的EcnNotifier邮件:

class EcnNotifier < ActionMailer::Base
  default from: "engineering_notices@wilfley.com"

  def notify_default(ecn)
    @ecn = ecn
    @email_list = EmailList.all
    mail to: "aaa@test.com", subject: 'ECN approval'
  end

  def distribute_engineering(ecn)
    @ecn = ecn
    @email_list = EmailList.all
    mail to: "abc@gmail.com", subject: 'ECN approval' 
  end

  def distribute_purchasing(ecn)
    @ecn = ecn
    @email_list = EmailList.all
    mail to: "abc@gmail.com", subject: 'ECN approval' 
  end

end

顺便说一下:如果你要发送多封邮件,你应该通过延迟工作宝石或类似的东西来做到这一点。否则用户必须等待很长时间,因为在发送所有邮件期间将阻止ruby进程。延迟的job gem可以在github上找到:https://github.com/collectiveidea/delayed_job