don*_*ald 10 ruby-on-rails devise ruby-on-rails-3
当用户注册我的服务时,如何发送欢迎电子邮件?
另外,如何更改电子邮件:来自Devise的from和:subject字段?
谢谢
Arc*_*lye 20
我不能使用"已批准"的答案,因为我没有使用Devise的:确认.
我不喜欢其他解决方案,因为你必须使用模型回调,即使你在控制台或管理界面中创建他的帐户,也会发送欢迎电子邮件.我的应用程序涉及从CSV文件批量导入用户的功能.我不希望我的应用程序逐个向所有3000个用户发送惊喜电子邮件,但我确实希望创建自己帐户的用户收到欢迎电子邮件.解决方案:
1)覆盖Devise的注册控制器:
#registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
def create
super
UserMailer.welcome(resource).deliver unless resource.invalid?
end
end
Run Code Online (Sandbox Code Playgroud)
2)告诉Devise你覆盖其注册控制器:
# routes.rb
devise_for :users, controllers: { registrations: "registrations" }
Run Code Online (Sandbox Code Playgroud)
当然,您可以调整"UserMailer"和"devise_for:users"以匹配您正在使用的型号名称.
Ben*_*zco 16
我是通过覆盖设计的确认来做到的!方法:https://gist.github.com/982181
class User < ActiveRecord::Base
devise :invitable, :database_authenticatable, :registerable, :recoverable,
:rememberable, :confirmable, :validatable, :encryptable
# ...
# devise confirm! method overriden
def confirm!
welcome_message
super
end
# ...
private
def welcome_message
UserMailer.welcome_message(self).deliver
end
end
Run Code Online (Sandbox Code Playgroud)
这是一个很好的讨论.覆盖benoror建议的方法会很有效.如果您认为您可能想要捕获其他用户事件,那么正如其他人在其他地方建议的那样,Observer类可能是最干净的方法.此解决方案适用于Rails 3.0.x和3.1.
要设置观察者,请对应用程序文件进行以下更改,将此观察者添加到您可能已有的任何其他人.
#config/application.rb
config.active_record.observers = :user_observer
Run Code Online (Sandbox Code Playgroud)
然后在models目录中创建一个新文件:
#app/models/user_observer.rb
class UserObserver < ActiveRecord::Observer
def after_create(user)
Notifier.user_new(user).deliver
end
end
Run Code Online (Sandbox Code Playgroud)
如果您有执行创建用户功能的黄瓜测试,则可以将此步骤添加到该功能,并使用工作步骤对其进行备份,以检查测试邮件阵列中的电子邮件.
#features/users/sign_up.feature for example
Scenario: User signs up with valid data
...
And I should receive an email with "[Text from your welcome message]"
#features/common_steps.rb
Then /^I should receive an email with "([^"]*)"$/ do |value|
# this will get the most recent email, so we can check the email headers and body.
ActionMailer::Base.deliveries.should_not be_empty
@email = ActionMailer::Base.deliveries.last
@email.body.should include(value)
#@email.from.should == ["no-reply@example.com"]
end
Run Code Online (Sandbox Code Playgroud)
您的环境/ test.rb应具有这些设置来构建邮件阵列而不是发送:
config.action_mailer.delivery_method = :test
config.action_mailer.perform_deliveries = true
Run Code Online (Sandbox Code Playgroud)
毋庸置疑,你可以在消息中测试更多(来自,来自等),但如果你这么倾向,这将使你以BDD的方式开始.
另请参阅一些较旧的StackOverflow线程,深入了解此问题包括:
| 归档时间: |
|
| 查看次数: |
10633 次 |
| 最近记录: |