密码确认不与密码比较

时间:2013-11-12 17:55:21

标签: ruby-on-rails ruby validation passwords

我不确定如何验证确认密码元素,此代码似乎有效,但验证密码确认似乎没有按预期比较密码,只需要一手熟悉Rails 4的新方法

注册视图:              注册

    <%= 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 %>
        <%= f.text_field :email, class: "form-control", autofocus: "", required: "", placeholder: "Email address" %>
        <%= f.password_field :password, class: "form-control", required: "", placeholder: "Password" %>
        <%= f.password_field :password_confirmation, class: "form-control", required: "", placeholder: "Confirm Password" %><br/>
        <p class="button"><%= submit_tag "Register", class: "btn btn-lg btn-primary btn-block" %></p>
    <% end %>
</div>

用户控制器:

class UsersController < ApplicationController
    def new
        @user = User.new
    end

    def create
        @user = User.create(user_params)
        if @user.save
            redirect_to root_url, :notice => "Signed up!"
        else
            render "new"
        end
    end
    private
    def user_params
        params.require(:user).permit(:username, :email, :password, :passord_confirmation, :salt, :encrypted_password)
    end
end

用户型号:

class User < ActiveRecord::Base

    attr_accessor :password
    before_save :encrypt_password

    validates_presence_of :password, on: :create
    validates :password, confirmation: :true
    validates_presence_of :email
    validates_uniqueness_of :email

    def self.authenticate(email, password)
        user = find_by_email(email)
        if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
            user
        else
            nil
        end
    end
    private
    def encrypt_password
        if password.present?
            self.password_salt = BCrypt::Engine.generate_salt
            self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
        end
    end
end

2 个答案:

答案 0 :(得分:0)

看起来您的模型的密码确认可能已关闭,除非您拥有自己的私有方法confirmation

尝试将模型从validates :password, confirmation: :true更改为validates_confirmation_of :password

API也有一些例子。

答案 1 :(得分:0)

您需要输入密码和password_confirmation。例如:

attr_accessor :password
attr_accessible :password, :password_confirmation

validates :password, :presence     => true,
                     :confirmation => true

尝试添加它,看看它是否有所作为。