我花时间研究,这是我能想到的
但是,我很确定这部分@users_emails += user.email
任何人都可以修复我的代码以使其正常工作吗?
控制器/ users_controller.rb
def send_all_at_once
@notification_users = User.where("users.country_id=?", 36)
@notification_users.each do |user|
@users_emails += user.email
end
@subject = "Test subject"
@body = "Test body"
CallMailer.call_email(@users_emails, @subject, @body).deliver
end
应用/邮寄者/ call_mailer.rb
class CallMailer < ActionMailer::Base
default :from => "dont-reply@example.com"
def call_email(@users_emails, @subject, @body)
mail(:to => "admin@example.com",
:bcc => @users_emails,
:subject => @subject,
:body => @body) do |format|
format.html
format.text
end
end
end
视图/ call_mailer / call_email.html.erb
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
</head>
<body>
<p>
You received a message.
</p>
<p>
Subject: <%= raw @subject %>
</p>
<blockquote>
<p>
<%= simple_format(@body) %>
</p>
</blockquote>
<p>
From: <%= link_to root_url,root_url %>
</p>
</body>
</html>
答案 0 :(得分:1)
通常,您将bcc的电子邮件地址作为数组传递:
mail(:to => "admin@example.com",
:bcc => ['first@email.com', 'second@email.com', 'third@email.com'],
:subject => @subject,
:body => @body)
但是,由于@user_emails
已经是一组电子邮件,您应该放弃括号并直接传递实例变量:
mail(:to => "admin@example.com",
:bcc => @users_emails,
:subject => @subject,
:body => @body)
以下描述了创建用户电子邮件数组的正确语法:
@notification_users.each do |user|
@users_emails << user.email
end
更新:
正如评论者mbratch精明地指出的那样,上面例子中的铲运算符可以用以下方式由plus-equals(+=
)运算符代替:
@user_emails = []
@notification_users.each do |user|
@users_emails += [user.email]
end
更新2:
您可以通过在mail
函数调用中直接映射用户电子邮件来完全绕过控制器循环:
mail(:to => "admin@example.com",
:bcc => User.where("users.country_id=?", 36).map(&:email),
:subject => @subject,
:body => @body)