0

I've spent time for research, and this is what I could think of.
But, I'm pretty sure there's something wrong with this part @users_emails += user.email

Can anyone fix my code to make it work?

controllers/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

app/mailers/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

views/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>
4

1 回答 1

1

通常,您会将密件抄送的电子邮件地址作为数组传递:

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 敏锐地指出的那样,上面示例中的 shovel 运算符可以通过+=以下方式替换为 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)
于 2013-07-22T17:51:16.920 回答