2012-03-26 70 views
0

嗨,我是一名紅寶石新手,我在更新用戶密碼時遇到問題,我如何驗證舊密碼與當前密碼?爲了改變它,密碼字段和password_confirmation字段不驗證!...這是我的users_controller代碼:...另外我還有一些錯誤sign_in (current_user,:bypass=>true),同時試圖保持用戶登錄時密碼更改在rails中更新密碼的問題

def edit 
@user=User.find(params[:id]) 
@title="Editar Informacion" 
end 

def update 
@user=User.find(params[:id]) 

if @user.update_attributes(params[:user]) 
    sign_in(current_user, :bypass => true) 
    flash[:success]="Profile updated" 
    redirect_to edit_user_path(current_user) 
else 
    @title="Edit user" 
    render 'edit' 
end 
end 

我的用戶模型:

attr_accessor :password 
attr_accessible :name,:email,:lastname,:password,:password_confirmation 

email_regex = /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z/i 

validates :name,:presence=>true, 
       :length=>{:maximum=>50} 

validates :lastname,:presence=>true, 
        :length=>{:maximum=>50} 

validates :email,:presence=>true, 
       :format=>{:with => email_regex}, 
       :uniqueness=> {:case_sensitive=>false} 

validates :password,:presence=>true, 
        :confirmation=>true, 
        :length=>{:within=>6..40}, 
        :on=>:create 

before_save :encrypt_password 

def has_password?(submitted_password) 
encrypted_password == encrypt(submitted_password) 
end 

def self.authenticate(email, submitted_password) 
user = find_by_email(email) 
return nil if user.nil? 
return user if user.has_password?(submitted_password) 
end 

而且我編輯觀點:

<%=form_for @user do |c| %> 
<%= render 'shared/error_messages', :object => c.object %> 
<table> 
<tr> 
    <td class="field"> 
      <%=c.label :old_password,"Contraseña anterior"%><br /> 
      <%=c.password_field :old_password%> 
    </td> 
</tr> 
<tr> 
    <td class="field"> 
      <%=c.label :password, "Contraseña"%><br /> 
      <%=c.password_field :password%>   
    </td> 
    <td class="actions" rowspan="3"> 
      <%=c.submit "Guardar Cambios"%> 
    </td> 
</tr> 
<tr> 
    <td class="field"> 
      <%=c.label :password_confirmation,"Confirmar Contraseña"%>   <br /> 
      <%=c.password_field :password_confirmation%> 
    </td> 
</tr> 
</table> 
<%end%> 

謝謝!

出現此錯誤:

NoMethodError in SessionsController#create 
You have a nil object when you didn't expect it! 
You might have expected an instance of Array. 
The error occurred while evaluating nil.[] 

我想我不能與當前密碼驗證正確的:old_password ...:S

回答

0

,以驗證密碼應該是不相等的嘗試:

validates :password_should_be_different 
    def password_should_be_different 
    if read_attribute(:password) == password 
     errors.add :password, "is similar!" 
    end 
    end 
+0

我有同樣的錯誤,它顯示在上面! – 2012-03-26 23:19:36

0

您需要在模型中添加:old_password和:password_confirmation to attr_accessor,並且:old_password to attr_accessible。它應該是這樣的:

attr_accessor :password, :password_confirmation, :old_password 
attr_accessible :name,:email,:lastname,:password,:password_confirmation, :old_password 

如果沒有定義屬性(使用attr_accessor),並使其可用於大規模分配(使用attr_accessible),它們將不被通過,您的驗證將失敗。