【发布时间】:2011-06-01 07:16:09
【问题描述】:
有没有办法创建after_confirmation :do_something?
目标是在用户使用 Devise :confirmable 确认后发送电子邮件。
【问题讨论】:
标签: ruby-on-rails rubygems ruby-on-rails-3 devise
有没有办法创建after_confirmation :do_something?
目标是在用户使用 Devise :confirmable 确认后发送电子邮件。
【问题讨论】:
标签: ruby-on-rails rubygems ruby-on-rails-3 devise
对于 devise 3.x 的新版本:
查看不同的答案http://stackoverflow.com/a/20630036/2832282
对于 devise 2.x 的旧版本:
(原答案)
但是您应该能够在用户上放置一个 before_save 回调(使用观察者的额外功劳)并检查confirmed_at 是否刚刚由设计设置。您可以执行以下操作:
send_the_email if self.confirmed_at_changed?
http://api.rubyonrails.org/classes/ActiveModel/Dirty.html 了解有关检查现场更改的更多详细信息。
【讨论】:
after_save :send_welcome_email, :if => proc { |l| l.confirmed_at_changed? && l.confirmed_at_was.nil? }
after_confirmation 可以在您的用户模型上覆盖
我也没有看到那个回调,也许你可以尝试覆盖确认方法并在那里调用你的回调。
def send_confirmation_instructions(attributes={})
super(attributes)
your_method_here
end
【讨论】:
您可以覆盖confirm! 方法:
def confirm!
super
do_something
end
关于该主题的讨论在https://github.com/plataformatec/devise/issues/812。他们说没有像 after_confirmation :do_something 这样的回调,因为这种方法需要很多不同的回调。
【讨论】:
confirm。
您可以覆盖模型上的confirm! 方法
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable
def confirm!
super
do_something
end
end
关于这个话题的讨论是https://github.com/plataformatec/devise/issues/812。我试过这个方法,效果很好。
【讨论】:
我们正在合并来自 @Bernát 和 @RyanJM 的答案:
def confirm!
super
if confirmed_at_changed? and confirmed_at_was.nil?
do_stuff
end
end
这似乎比单独的两个答案更具性能意识和安全性。
【讨论】:
我使用的是 Devise 3.1.2,它有一个占位符方法after_confirmation,在确认成功完成后调用。我们只需要在User模型中重写这个方法。
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable
# Override Devise::Confirmable#after_confirmation
def after_confirmation
# Do something...
end
end
参见:Devise 3.5.9 源代码:https://github.com/plataformatec/devise/blob/d293e00ef5f431129108c1cbebe942b32e6ba616/lib/devise/models/confirmable.rb
导轨 4:
结合以上多个答案
def first_confirmation?
previous_changes[:confirmed_at] && previous_changes[:confirmed_at].first.nil?
end
def confirm!
super
if first_confirmation?
# do first confirmation stuff
end
end
【讨论】:
根据 Devise 3.5.9 源码,你可以简单地在 Devise Resource 模型上定义一个方法,例如:
class User < ActiveRecord::Base
...
def after_confirmation
do_something
end
end
参见:Devise 3.5.9 源代码:https://github.com/plataformatec/devise/blob/d293e00ef5f431129108c1cbebe942b32e6ba616/lib/devise/models/confirmable.rb
【讨论】: