Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

ruby on rails - Loop working but mailer not

I have a method that basically mails out a notification that someone has submitted a form in my app. I recently changed my models around so that multiple people can be notified by adding a user_designations model to handle all of the assignments (which school(s) a user is assigned to, etc.)

The method:

  def new_message(applicant)
    @applicant = applicant
    @applicant.school.users.each do |user|
        mail(:to => user.email, :subject => "Submitted Application")
    end
  end

Objects :

class Applicant
  belongs_to :school

class School 
  has_many :applicants
  has_many :user_designations
  has_many :users, :through => :user_designations

class User 
  has_many :schools, :through => :user_designations
  has_many :applicants, :through => :schools

The mail function is only working for the last iteration through the loop. I am also getting an error:

undefined method `user' for #School:0x007fe064700890

Any ideas based on this small amount of information?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In ActionMailer subclasses, each mailer action constructs an internal representation of a mail message when invoked, for Rails to deliver. In your loop, you are simply reconstructing the same mail message, over and over again, so only the last iteration of the loop survives - that's simply the way ActionMailer was written.

If you'd like to deliver to multiple recipients, you have a few options:

  • Use a loop where you're calling the mailer ( Mailer.new_message(...).deliver )
  • Use multiple addresses in To/CC/BCC in your mailer

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...