使用Devise时未定义的方法confirmed_at

时间:2015-10-30 09:40:08

标签: ruby-on-rails ruby devise devise-confirmable

尝试使用Devise的:confirmable模块时出现以下错误:

NameError (undefined local variable or method `confirmed_at' for #<AdminUser:0x007f27841d0f30>)

我的模特:

class AdminUser < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable,:recoverable, :rememberable, :trackable, :validatable, :confirmable

  after_create { |admin| admin.send_reset_password_instructions }
  def password_required?
    new_record? ? false : super
  end
end

我想在创建AdminUser时发送确认电子邮件。

3 个答案:

答案 0 :(得分:6)

仅仅在模型中添加:confirmable选项是不够的,您还需要将Devise所需的列添加到数据库表中。

假设您使用的是模型AdminUser

class AddConfirmableToDevise < ActiveRecord::Migration
  def self.up
    add_column :admin_users, :confirmation_token,   :string
    add_column :admin_users, :confirmed_at,         :datetime
    add_column :admin_users, :confirmation_sent_at, :datetime
    add_column :admin_users, :unconfirmed_email,    :string

    add_index  :admin_users, :confirmation_token, :unique => true
  end

  def self.down
    remove_index  :admin_users, :confirmation_token

    remove_column :admin_users, :unconfirmed_email
    remove_column :admin_users, :confirmation_sent_at
    remove_column :admin_users, :confirmed_at
    remove_column :admin_users, :confirmation_token
  end
end

答案 1 :(得分:3)

只需运行命令:

rails g migration add_confirmable_to_devise

分贝/迁移/ YYYYMMDDxxx_add_confirmable_to_devise.rb

class AddConfirmableToDevise < ActiveRecord::Migration
  # Note: You can't use change, as User.update_all will fail in the down migration
  def up
    add_column :users, :confirmation_token, :string
    add_column :users, :confirmed_at, :datetime
    add_column :users, :confirmation_sent_at, :datetime
    add_index :users, :confirmation_token, unique: true
    execute("UPDATE users SET confirmed_at = NOW()")
  end

  def down
    remove_columns :users, :confirmation_token, :confirmed_at, :confirmation_sent_at
  end
end

进一步参考devise

答案 2 :(得分:2)

您将:confirmable放入AdminUser模型中。因此,您需要具有可确认功能的列,包括confirmed_at

您应该有一个Devise生成的迁移文件。在该文件中,您需要删除confirmable列的注释,包括created_at