开发者

Rails 3 + action mailer - Cannot loop to send emails

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" <beatrix@example.com>',
            :subject => "#{project.owner.name} created a new project")
    end
end

Testing with a user that has 2 followers:

User.find(1).followers.count = 2

开发者_如何学Go

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


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" <beatrix@example.com>',
         :subject => "#{project.owner.name} created a new project")
end


You can also move the .deliver call into your new_project method. This works for me using Rails 3:

def new_project(project)
  # ...
  @followers.each do |f|
    # ...
    mail(:to => @u.email,
         :from => '"Beatrix Kiddo" <beatrix@example.com>',
         :subject => "#{project.owner.name} created a new project").deliver
  end
end

To send the mails, you would use

if @project.save
   # ...
   UserMailer.new_project(@project)
else
   # ...
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜