Joe*_*Joe 18 validation password-confirmation ruby-on-rails-3
我无法弄清楚为什么模型不会检查密码确认,这是模型的代码:
class User < ActiveRecord::Base
attr_accessor :password_confirmation
validates :email, :presence =>true,
:uniqueness=>true
validates :password, :presence =>true,
:length => { :minimum => 5, :maximum => 40 },
:confirmation =>true
validates_confirmation_of :password
end
Run Code Online (Sandbox Code Playgroud)
控制器用于从视图中获取数据并尝试执行保存,这是视图的代码:
<h1>Registration process</h1>
<%= form_for(@new_user) do |f|%>
<% if @new_user.errors.any? %>
<div id="errorExplanation">
<h2><%= pluralize(@new_user.errors.count, "error") %> prohibited this article from being saved:</h2>
<ul>
<% @new_user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% 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 %>
<%#TODO Confirm password%>
<%= f.submit 'Join' %>
<%end%>
Run Code Online (Sandbox Code Playgroud)
如果密码不匹配,则不会出现错误.
Soo*_*uNe 36
我也被这个人烧了.我怀疑你的确认价值是nil.来自文档:
注意:仅当password_confirmation不为nil时才执行此检查,默认情况下仅在保存时执行.要确认,请确保为确认属性添加状态检查:
此外,您不需要attr_accessor :password_confirmation,因为验证会为您添加.Rails的!