Rails设计:after_confirmation

don*_*ald 33 rubygems ruby-on-rails devise ruby-on-rails-3

有没有办法创造一个after_confirmation :do_something

目标是在用户确认使用Devise后发送电子邮件:confirmable.

Blu*_*ith 84

我正在使用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
Run Code Online (Sandbox Code Playgroud)

请参阅:Devise 3.5.9源代码:https://github.com/plataformatec/devise/blob/d293e00ef5f431129108c1cbebe942b32e6ba616/lib/devise/models/confirmable.rb

  • 这是正确的,非常有帮助的.谢谢! (2认同)

njo*_*den 24

对于新版本的devise 3.x:

查看其他答案http://stackoverflow.com/a/20630036/2832282

对于旧版本的devise 2.x:

(原始答案)

但是你应该能够在用户上放置一个before_save回调(使用观察者的额外功劳),并检查confirm_at是否只是由设计设置的.你可以这样做:

  send_the_email if self.confirmed_at_changed?
Run Code Online (Sandbox Code Playgroud)

有关检查字段更改的更多详细信息,请访问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?}` (23认同)
  • 对于未来的读者,[这个答案](http://stackoverflow.com/a/20630036/2832282) 强调现在有一个官方回调 `after_confirmation` 可以在你的用户模型上覆盖 (2认同)

Ber*_*nát 10

您可以覆盖该confirm!方法:

def confirm!
  super
  do_something
end
Run Code Online (Sandbox Code Playgroud)

有关该主题的讨论,访问https://github.com/plataformatec/devise/issues/812.他们说没有回调,比如after_confirmation :do_something因为这种方法需要很多不同的回调.


nol*_*oli 5

导轨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
Run Code Online (Sandbox Code Playgroud)