如何在rails中为多个模型发送邮件

时间:2013-08-09 04:50:51

标签: ruby-on-rails

我是铁杆新手。我在邮件发送到多个模型时遇到问题。我们的项目包含家长,教师和学生模型。每个模块都有用户数(学生,家长,教师)。而且我有三个复选框。那是学生,老师,家长。当我点击学生和老师时,邮件应该发送给所有老师和所有学生。

如果我想向老师发送邮件而且学生意味着,这背后的问题,邮件只发送给老师而不是学生。如何解决这个问题。我加入了我的编码。

控制器

def send_news_letter  

     if params[:announcement].present?
        @announcement = Announcement.find(params[:announcement].keys).first
      end
    if params[:students].present? and params[:teachers].present?
        @student = Student.pluck(:email)
        @teacher = Teacher.pluck(:email)
        UserMailer.send_multiple_email(@student,@teacher,@announcement).deliver
        redirect_to announcements_url, :notice => "Newsletter Delivered Successfully" a
      end

Usermailer.rb

class UserMailer < ActionMailer::Base
  default to: Proc.new {Teacher.pluck(:email)},
          to: Proc.new {Student.pluck(:email)}, 
          from: "from@example.com"


  # Subject can be set in your I18n file at config/locales/en.yml
  # with the following lookup:
  #
  #   en.user_mailer.password_reset.subject
  #
  def password_reset(user)
   @user = user
   mail :to => user.email, :subject => "Password Reset"
  end

  def send_multiple_email(user,employee,announcement)
   @user = user
   @employee = employee
   @announcement = announcement
   mail :subject => "Deliver"
   end


end

请帮帮我。谢谢。

1 个答案:

答案 0 :(得分:0)

首先,在你的控制器中,我将所有地址存储在一个数组中:

@emails = []
if params[:students].present?
  @emails += Student.pluck(:email)
end
if params[:teachers].present?
  @emails += Teacher.pluck(:email)
end
if params[:parents].present?
  @emails += Parent.pluck(:email)
end

UserMailer.send_multiple_email(@emails,@announcement).deliver

然后在你的邮件程序中改为:

def send_multiple_email(emails,announcement)
  @announcement = announcement
  emails.each do | address |
    mail :to => address, :subject => "Deliver"
  end
end

请注意,如果您在邮件程序模板中引用模型(例如“Hi <%= @user.name %>!”),则需要加载整个模型对象。现在,您只需使用pluck获取要发送到的所有地址的列表。要获取整个模型,请将控制器中的pluck(:email)更改为all,然后更改邮件程序以引用该模型中的属性。这也意味着您的三个模型需要具有相同的属性名称(至少是您打算在邮件程序中使用的属性名称)。

希望它有意义。