2012-05-16 39 views
1

最近,我将密码验证代码更改为下面的代码,以便我可以创建一个不需要密码和密码确认的表单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 

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

ActiveRecord::RecordInvalid in PasswordResetsController#create

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

T他在我尝试为现有用户生成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 %> 

让我知道,如果你们需要的任何其他文件。

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

谢谢。

+0

解决它。 ':allow_blank => true'将使这个工作。 – Huy

回答

1

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

validates :password, length:  { minimum: 8, allow_nil: true }, 
         confirmation: true 
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