0

我的密码确认验证有问题

在用户模型中:

 validates :password, :confirmation => true

在视图 new.html.erb 中:

 <%= form_for(@user) do |f| %>
   <div class="field">
     <%= f.label :password %><br />
     <%= f.password_field :password %><br />
     <%= f.label :password_confirmation %><br />
     <%= f.password_field :password_confirmation %><br />
   </div>
   <div class="actions">
     <%= f.submit %>
   </div>
 <% end %>

所以对于任何插入的数据,验证都会抛出错误。我认为 :password_confirmation 有问题,并且 RoR 收到它的值为 nil 是否可能?我能怎么做?

4

1 回答 1

1

尝试这个

class User < ActiveRecord::Base
  validates :password, :presence =>true, :confirmation =>true
  validates_confirmation_of :password
end

控制器旨在从视图中获取数据并尝试执行保存,这是视图的代码:

<%= form_for(@user) do |f|%>
  <% if @user.errors.any? %>
    ....
    ....
  <% end %>
  <%= f.label :email %><br />
  <%= f.text_field :email %><br />
  <%= f.label :password %><br />
  <%= f.password_field :password %><br />
  <%= f.label :password_confirmation %><br />
  <%= f.password_field :password_confirmation %>
  <%= f.submit %>
<% end %>


NOTE: This check is performed only if password_confirmation is not nil, and by default    only on save. 
To require confirmation, make sure to add a presence check for the confirmation attribute:

http://ar.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html

于 2012-10-05T12:53:14.383 回答