ruby on rails password_confirmation validation

时间:2012-10-05 12:47:45

标签: ruby-on-rails-3 validation password-confirmation

我遇到密码确认验证问题

用户模型中的

 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以零值接收它 它有可能吗?我该怎么办?

1 个答案:

答案 0 :(得分:1)

试试这个

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

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

<%= 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