1

我不确定如何验证确认密码元素,此代码似乎有效,但验证密码的确认似乎并没有按预期比较密码,只需要一个手习惯 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
4

2 回答 2

0

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

尝试将您的模型从更改validates :password, confirmation: :truevalidates_confirmation_of :password

API也有一些示例。

于 2013-11-12T18:58:37.127 回答
0

您需要使密码和密码确认可访问。例如:

attr_accessor :password
attr_accessible :password, :password_confirmation

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

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

于 2013-11-12T19:14:38.213 回答