Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 + action mailer - Cannot loop to send emails

Tags:

A user can create an object, and he has followers that I want to alert when he creates this object.

controller:

if @project.save   format.html { redirect_to(@project, :notice => 'Project was successfully created.') }   format.xml  { render :xml => @project, :status => :created, :location => @project }   # Send a notification to project owner's followers :   UserMailer.new_project(@project).deliver else   ... 

user_mailer.rb:

def new_project(project)     @url  = "http://localhost:3000/"     @project = project     # For each of project owner's follower, send an email notification     @followers = project.owner.followers.all     @followers.each do |f|         @u = User.find(f.follower)         mail(   :to => @u.email,             :from => '"Beatrix Kiddo" <[email protected]>',             :subject => "#{project.owner.name} created a new project")     end end 

Testing with a user that has 2 followers:
User.find(1).followers.count = 2

Follower.follower is the id of the user who's following.

Only 1 email is sent to the 1st follower, and the 2nd doesn't receive anything - what's wrong?

[SOLVED] => the .deliver method simply doesn't support multiple messages. Thx DR

like image 805
Laurent Avatar asked Mar 14 '11 09:03

Laurent


1 Answers

ActionMailer does not support sending multiple messages with one deliver call. You have to move the loop outside of the new_project method:

Instead of

UserMailer.new_project(@project).deliver 

try this:

@followers = @project.owner.followers.all @followers.each do |f|     UserMailer.new_project(@project, f).deliver end 

The new_project method then could look like this:

def new_project(project, follower)     @u = User.find(f.follower)     mail(:to => @u.email,          :from => '"Beatrix Kiddo" <[email protected]>',          :subject => "#{project.owner.name} created a new project") end 
like image 177
Daniel Rikowski Avatar answered Dec 14 '22 07:12

Daniel Rikowski