【问题标题】:ruby on rails password_confirmation validationruby on rails password_confirmation 验证
【发布时间】:2012-10-05 12:47:44
【问题描述】:

密码确认验证有问题

在用户模型中:

 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 有可能吗?我该怎么办?

【问题讨论】:

  • 你能粘贴错误吗?
  • 根据您发布的内容无法为您提供帮助。我们将不得不看看您如何尝试将参数分配给您的模型。另外,无论如何你都不应该这样做。在 Rails 3+ 中使用 has_secure_password
  • 这不是错误...当我插入密码和 password_confirmation 表单字段并单击“提交”时,仍然在同一页面中,并且消息错误,无法保存:密码和他的确认是不同的。

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


【解决方案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

【讨论】:

  • 我明白了……但它看起来像第一个版本,不是吗?
  • 我试过了。现在它给了我两次错误! 2 个错误禁止保存此用户:密码不一致 con la conferma 密码不一致 con la conferma
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-09
  • 2011-07-04
  • 2016-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多