[英]Sending email to all admins upon user sign up in Ruby
I have followed the ruby on rails tutorial in my design of a web app and am now venturing off on my own to add in some functionality that isn't covered in the tutorial. 我在设计Web应用程序时遵循了ruby on rails教程,现在我自己冒险尝试添加一些本教程未涵盖的功能。
Currently, I am trying to send an email to all users with the admin role. 目前,我正在尝试向所有具有管理员角色的用户发送电子邮件。 The admin role is implemented in the tutorial as a boolean field admin on the user model.
admin角色在本教程中作为用户模型上的布尔字段admin实现。 I tried to do this by the following method:
我试图通过以下方法做到这一点:
When @user.send_activation_email
is called in the create method in user_controller.rb, it goes to the definition in user.rb 在user_controller.rb中的create方法中调用
@user.send_activation_email
,将转到user.rb中的定义
def send_activation_email
UserMailer.account_activation(self).deliver_now
UserMailer.user_signed_up(self).deliver_now # my modified code
end
I created user_signed_up
in the user_mailer.rb 我在user_mailer.rb中创建了
user_signed_up
def user_signed_up(user)
@user = user
# Send email to all admins that user has signed up
User.find_by_admin("true") do |admin|
mail to: admin.email, subject: "A new user has signed up"
end
end
but when I test this functionality in the user_mailer_test.rb with 但是当我在user_mailer_test.rb中使用
test "user_signed_up" do
user = users(:archer)
mail = UserMailer.user_signed_up(user)
assert_equal "A new user has signed up", mail.subject
User.find_by_admin("true") do |admin|
assert_equal [admin.email], mail.to
assert_equal ["noreply@example.com"], mail.from
end
end
I get that the tests fails on assert_equal "A new user has signed up", mail.subject
. 我发现在
assert_equal "A new user has signed up", mail.subject
上测试失败。 It looks like all that works, but it never enters the do loop of administrators. 看起来一切正常,但它从未进入管理员的do循环。 Am I querying the database incorrectly?
我查询数据库不正确吗? Is there a better way to do this?
有一个更好的方法吗? I found this, but I'm not sure how to implement it
我找到了,但是我不确定如何实现
class AdminMailer < ActionMailer::Base
default to: Proc.new { Admin.pluck(:email) },
from: 'notification@example.com'
def new_registration(user)
@user = user
mail(subject: "New User Signup: #{@user.email}")
end
end
Would that be a better choice? 那会是更好的选择吗?
I'm guessing it "never enters the do loop of administrators" because User.find_by_admin("true")
isn't returning any records, ie there are no administrators to loop through. 我猜它“永远不会进入管理员的do循环”,因为
User.find_by_admin("true")
不会返回任何记录,即没有管理员可以循环。 Did you perhaps mean User.find_by_admin(true)
? 您可能是说
User.find_by_admin(true)
吗?
Regardless, I think you're approaching this wrong: You should just send one email to eg admins@example.com
and have that mailbox forward all messages to all of your admins. 无论如何,我认为您正在解决此错误:您应该只向例如
admins@example.com
发送一封电子邮件,并让该邮箱将所有消息转发给您的所有管理员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.