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?
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:
Mailer.new_message(...).deliver)