重置密码验证错误:即使密码在范围内,密码也会出现错误

时间:2012-05-16 03:00:51

标签: ruby-on-rails ruby-on-rails-3

最近,我将密码验证的代码更改为以下代码,以便我可以创建一个不需要密码和密码确认How to only change one attribute in a model using form_for in Rails的表单。

请注意,我没有使用has_secure_password来生成加密密码。我在RailsTutorial中使用了每个Hartl的SHA2.hexdigest。

user.rb

before_save :encrypt_password, :unless => Proc.new { |u| u.password.blank? }
validates_presence_of :password, :if => :should_validate_password?
validates_confirmation_of :password, :if => :should_validate_password?
validates_length_of :password, :minimum => 6, :maximum => 40, :allow_blank => true
#changing :allow_blank from false to true above fixed my problem.

def should_validate_password?
  updating_password || new_record?
end

我在记住我/重置密码http://railscasts.com/episodes/274-remember-me-reset-password上关注了这个Railscast,我不断收到此错误:

ActiveRecord::RecordInvalid in PasswordResetsController#create

Validation failed: Password is too short (minimum is 6 characters)

当我尝试为现有用户生成auth_tokens时,以及当我尝试为重置链接提交电子邮件时再次发生这种情况。我可以通过注释掉这段代码暂时删除这个验证,一切正常。

我尝试重新登录用户帐户以更改密码,使其在范围内(长度为9个字符),但我仍然收到相同长度的验证错误消息。

任何提示?

我不知道问题源于何处。我不明白为什么我的密码正在验证。

以下是我的密码重置控制器中的创建操作:

def create
  user = User.find_by_email(params[:email])
  user.send_password_reset if user
  redirect_to root_path, :notice => "Email sent with password reset"
end

这是我的密码重置表单:

<%= form_tag password_resets_path, :method => :post do %>
  <div class="field">
    <%= label_tag :email %>
    <%= text_field_tag :email, params[:email] %>
  </div>
  <div class="actions"><%= submit_tag "Reset Password" %></div>
<% end %>

如果您需要任何其他文件,请告诉我。

编辑:使用工作解决方案更改代码。

感谢。

2 个答案:

答案 0 :(得分:1)

出现错误是因为您验证了password_confirmation。这意味着它也会期望一个范围内的值。

您可以通过执行以下操作来解决此问题:

validates :password,  length:     { minimum: 8, allow_nil: true },
                      confirmation: true

答案 1 :(得分:1)

您不需要:should_validate_password?

我刚刚添加了一个Proc如下:

validates :password, length: { minimum: 6 }, unless: Proc.new { |user| user.password.nil? }
validates :password_confirmation, presence: true, unless: Proc.new { |user| user.password.nil? }

或者您可以使用with_options

对此进行分组

请参阅:http://guides.rubyonrails.org/v3.2.13/active_record_validations_callbacks.html