Rails 3 + action mailer - Cannot loop to send emails

拜拜、爱过 提交于 2019-12-30 00:50:29

问题


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

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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/5296687/rails-3-action-mailer-cannot-loop-to-send-emails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!