将current_user.id传递给actionmailer

时间:2015-02-10 14:12:34

标签: ruby-on-rails actionmailer

我试图将current_employer.id传递给动作邮件程序。所以我可以向属于雇主的用户发送电子邮件。

我的邮件看起来像这样。

class ScheduleMailer < ActionMailer::Base

  default to: Proc.new { Employee.where(:employer_id => current_employer.id
       ).pluck(:email) },
       from: 'noreply@scheduled.com'



 def schedule_post_reg(employ)

 mail( :subject => "Your schedule has been posted.")

 end


 end

我收到此错误

 NameError (undefined local variable or method `current_employer' for #<ScheduleMailer:0x0000010cec0880>):
  app/mailers/schedule_mailer.rb:3:in `block in <class:ScheduleMailer>'
  app/mailers/schedule_mailer.rb:10:in `schedule_post_reg'
  app/controllers/schedules_controller.rb:235:in `approve_shift'

关于如何传递current_employer.id而不是动作管理器的任何建议将不胜感激。

2 个答案:

答案 0 :(得分:1)

Mailer无法直接访问请求上下文。原因是因为电子邮件不一定是HTTP请求的结果。例如,如果您从CLI发送电子邮件,则没有HTTP请求。

您需要传递employer作为邮件的参数。

class ScheduleMailer < ActionMailer::Base

  default from: 'noreply@usescheduled.com'

  def schedule_post_reg(employee, employ)
    mail({
      :to => employee.email
      :subject => "Your schedule has been posted.")
    })
  end

end

如果您需要向同一个雇主发送相同的电子邮件,您可以通过雇主并将所有电子邮件发送到&#34;至:&#34;字段(但所有收件人都会看到所有其他电子邮件)

  def schedule_post_reg(employer, employ)
    mail({
      :to => Employee.where(:employer_id => employer.id).pluck(:email)
      :subject => "Your schedule has been posted.")
    })
  end

或使用bcc,或循环播放所有电子邮件,并为每位员工电子邮件致电邮件一次,为每位员工生成不同的电子邮件。

答案 1 :(得分:0)

在Controller中写这样的东西

@employer = Employer.find_by_id(params[:id])
ScheduleMailer.schedule_post_reg(employ, @employer).deliver

在梅勒

def schedule_post_reg(employ, employer)
    employees_emails = Employee.where(:employer_id => employer.id
   ).map(&:email).join(",")
    mail(:to => employees_emails, :subject => "Your schedule has been posted.")
end