【问题标题】:Password Confirmation with has_secure_password使用 has_secure_password 确认密码
【发布时间】:2014-06-09 13:38:15
【问题描述】:

我在我的User 模型中使用has_secure_password 行。它看起来像这样:

class User < ActiveRecord::Base
    before_create :create_remember_token
  validates :name, presence: true, length: {minimum: 3, maximum: 22},
                            uniqueness: true
  #validates :password, presence: true, length: {minimum: 6, maximum: 22}
    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+\.[a-z]+\z/i
    validates :email, :allow_blank => true, format: { with: VALID_EMAIL_REGEX }
  has_secure_password
  validates :password, length: {minimum: 6}

在我的Users 新视图中,我有这个:

<h1>Sign up</h1>

<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_for(@user) do |f| %>

      <%= f.label :name, 'Username' %>
      <%= f.text_field :name %>

      <%= f.label :email, 'Email (Optional)' %>
      <%= f.text_field :email %>

      <%= f.label :password %>
      <%= f.password_field :password %>

      <%= f.label :password_confirmation, "Confirmation" %>
      <%= f.password_field :password_confirmation %>

      <%= f.submit "Create my account", class: "btn btn-large btn-primary" %>
    <% end %>
  </div>
</div>

根据我的阅读,has_secure_password 位应该“自动”创建和验证密码确认内容。但是,当我使用不匹配的password 和password_confirmation 创建用户时,它不会抛出任何东西。

任何想法我哪里出错了?

EDIT: forgot this       params.require(:user).permit(:name, :email, :password,
       line right here----->                       :password_confirmation)

【问题讨论】:

  • 可以发users_controller.rb的代码吗?特别是user_params part.
  • @ekremkrc 哦,天哪。我刚刚发现了问题。我的 user_param 位丢失了:password_confirmation。感谢您为我指明正确的方向

标签: ruby-on-rails ruby-on-rails-4 activemodel


【解决方案1】:

根据您的问题,我不确定用户是在没有匹配密码的情况下创建的并且是确认的,或者是否只显示错误消息。所以我会尝试回答这两个问题。

表单不会抛出有关错误的信息,因为您没有代码可以查看它。在表单开头添加这段代码以在表单中显示 flash 错误。

<%= form_for @user do |f| %>
  <% if @user.errors.any? %>
    <div class="error_messages">
      <h2>Form is invalid</h2>
      <ul>
        <% for message in @user.errors.full_messages %>
          <li><%= message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>
....

这里可能有其他问题:

    has_secure_password
    validates :password, length: {minimum: 6}

您验证了密码的最小长度,但不是它的存在。尝试更改第二行: 验证:密码,存在:真,长度:{最小值:6}

如果不起作用,请确保访问模型(rails 3)或控制器(rails 4)中的密码和密码确认字段:

如果您使用 rails 3,则应在模型中添加代码以访问您不希望在表单中允许的所有参数:

app/models/user.rb
attr_accessible :name, :email, :password, :password_confirmation

如果你使用rails 4,它应该是这样的:

app/controllers/users_controller.rb
def user_params
  params.require(:user).permit(:name, :email, :password, :password_confirmation)
end

希望它会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-05
    • 2012-04-03
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多