0

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

如果我想给老师和学生发送邮件,这背后的问题是,邮件只发送给老师而不是学生。如何解决这个问题。我包括了我的编码。

控制器

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

结尾

用户邮件程序.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

请帮助我。在此先感谢。

4

1 回答 1

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,并更改您的邮件程序以引用该模型中的属性。这也意味着您的三个模型需要具有相同的属性名称(至少是您打算在邮件程序中使用的名称)。

希望这是有道理的。

于 2013-08-09T06:13:17.887 回答