用户可以创建一个对象,并且他在创建此对象时会有我想要提醒的关注者。
控制器:
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
使用有2个关注者的用户进行测试:
User.find(1).followers.count = 2
Follower.follower
是正在关注的用户的id
。
只有1封电子邮件发送给第一个粉丝,第二封邮件没有收到任何内容 - 出了什么问题?
[已解决] =&gt; .deliver
方法根本不支持多条消息。谢谢DR
答案 0 :(得分:37)
ActionMailer不支持通过一次deliver
调用发送多封邮件。
您必须将循环移到new_project
方法之外:
而不是
UserMailer.new_project(@project).deliver
试试这个:
@followers = @project.owner.followers.all
@followers.each do |f|
UserMailer.new_project(@project, f).deliver
end
new_project
方法可能如下所示:
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
答案 1 :(得分:6)
您也可以将.deliver调用移动到new_project
方法中。这适用于我使用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
要发送邮件,您可以使用
if @project.save
# ...
UserMailer.new_project(@project)
else
# ...
end