【问题标题】:Getting two errors for password presence in activerecord在活动记录中出现密码存在两个错误
【发布时间】:2019-01-25 22:06:49
【问题描述】:

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

这是我为我的模型写的。

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

下面是我的迁移表:

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_digest 变量,一旦数据保留在数据库中,它就是用户密码的加盐哈希。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord sinatra


    【解决方案1】:

    has_secure_passwordcreate 操作中带有自己的存在验证。因此,验证 password 的存在是多余的,并且会导致您收到两条“密码不能为空”的错误消息。

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

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    • 2016-11-20
    • 1970-01-01
    相关资源
    最近更新 更多