在 activerecord 中出现两个密码错误

Getting two errors for password presence in activerecord

我正在我的应用程序中测试我的用户输入验证,我收到两个关于我的密码存在的错误。

这是我为我的模型写的。

class User < ActiveRecord::Base
  include Slugifiable
  extend Slugifiable::Find

  has_secure_password
  has_many :posts

  validates :email, uniqueness: true, presence: true
  validates :username, uniqueness: true, presence: true
  validates :password, presence: true

end

下面是我的迁移 table:

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :email
      t.string :username
      t.string :password
      t.string :password_digest
    end
  end
end

每次我 运行 我的应用程序没有输入时,它应该给我三个错误消息:"Password can't be blank"、"Email can't be blank"、"Username can't be blank"。相反,我得到一个额外的 "Password can't be blank" 错误。我正在使用 password_digest 变量,一旦数据保存在数据库中,它就是用户密码的加盐哈希值。

has_secure_passwordcreate 操作进行了自己的存在验证。因此,验证 password 的存在是多余的,并且会导致您收到两条 "Password can't be blank" 错误消息。

只需删除 validates :password, presence: true 或为特定控制器 action/other 上下文的验证添加条件...即

validates :password, presence: true, on: :some_action