【问题标题】:Rails password_confirmation not workingRails 密码确认不起作用
【发布时间】:2017-08-16 08:24:04
【问题描述】:

我需要帮助获取我的用户注册表单以验证密码和密码确认是否完全匹配。

目前表单会将输入的数据传递到数据库中的密码摘要字段并接受密码确认字段中的任何输入,并且不会给出任何错误。

我的代码如下;

模型 - user.rb

class User < ApplicationRecord

    before_save { self.email = email.downcase }
    #attr_accessible :user_name, :email
    validates_confirmation_of :password
    has_secure_password

    validates :user_name, presence: true, length: { maximum: 25 }
    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
    validates :email, presence: true, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX }
    validates :password, presence: true, confirmation: true, length: { minimum: 6 }

    has_many :trips
    has_many :countries, through: :trips

end

查看 - new.html.erb

<div class="container">
  <h1 class="text-center" style="margin-top: 10px;" >Sign up</h1>
  <div class="row">
    <div class="col-md-6 offset-md-3 ">
      <%=form_for(@user) do |f| %>
      <%= render 'shared/error_messages' %>
      <div class="form-group">
        <%= f.label :user_name, "Username" %>
        <%= f.text_field :user_name, class: "form-control" %>
      </div>

      <div class="form-group">
        <%= f.label :email %>
        <%= f.email_field :email, class: "form-control" %>
      </div>

      <div class="form-group">
        <%= f.label :password %>
        <%= f.password_field :password, class: "form-control" %>
      </div>

      <div class="form-group">
        <%= f.label :password_confirmation, "Password Confirmation" %>
        <%= f.password_field :password_confirmation, class: "form-control" %>
      </div>

      <div class="form-group">
        <%= f.submit "Create an account", class: 'form-control btn btn-primary' %>
      </div>
      <% end %> 
    </div>
  </div>
</div>

我的 gemfile 中也有 bcrypt -v 3.1.7。如果需要任何其他信息,请告诉我,我很乐意提供。

【问题讨论】:

  • 你的表中有密码摘要列吗?
  • 你的控制器怎么样?

标签: ruby-on-rails ruby


【解决方案1】:

我认为您没有获得密码确认,为此您应该添加

validates :password_confirmation, presence: true

此外,在您的控制器中,您应该将 :password_confirmation 列入您的许可部分。

Validates Confirmation 仅在 password_confirmation 不为零时进行验证。

【讨论】:

  • 谢谢,我认为问题出在控制器中,我的许可证中包含 :password_confirmation。奇怪的是,我最初在 for :password_confirmation 中有 validates 语句,但它在表单中给了我一个错误,所以我把它拿出来了。但是,我进行了两项更改,现在它正在工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-22
  • 2016-12-21
  • 1970-01-01
  • 1970-01-01
  • 2016-12-22
  • 2015-01-06
  • 2014-02-14
相关资源
最近更新 更多