2012-10-31 30 views
1

我想在我的rails應用程序中添加'更改密碼'功能,我從這裏研究它(207.44.138.58/~rorexper/viewtopic.php?t=690 & highlight = & sid = 16f7417dcbb3cb8960912c8134351fd9)ROR:undefined method`authenticate'

在我看來,我頁補充: -

= form_tag :action => 'update' do 
    - flash.each do |key, value| 
    %div.TxtRed{:class => "flash #{key}"}= value 
    %p 
    %label Current password 
    %br 
    = password_field_tag "user[current_password]", nil 
    %p 
    %label New password 
    %br 
    = password_field_tag "user[password]", nil 
    %p 
    %label Confirm password 
    %br 
    = password_field_tag "user[password_confirmation]", nil 
    %P 
    = button_tag "Save", :class => "btn-custom ML10", :type => :submit 

並在控制器: -

def update 
    return unless request.post? 
    @user = Refinery::User.find_by_id(current_user.id) 
    if current_user = Refinery::User.authenticate(@user.username, params[:user][:current_password]) 

     if (params[:user][:password] == params[:user][:password_confirmation]) 

      current_user.encrypted_password = crypted_password(params[:user] [:password] ,current_user.salt) 

      flash[:notice] = current_user.save ?"Password changed" :"Password not changed" 
      redirect_to my_page_path 

     else 

      flash[:notice] = "Password mismatch" 
      @current_password = params[:current_password] 

     end 

    else 

     flash[:notice] = "Wrong password" 

    end 
end 

def crypted_password(password, salt) 
    string_to_hash = password + "nyros" + salt 
    Digest::SHA1.hexdigest(string_to_hash) 
end 

但它不能正常工作並給出了一個錯誤: 「未定義的方法`驗證'爲#」

回答

0

如果從其調用的對象爲零,則authenticate方法將引發異常。換句話說,find_by未找到匹配的用戶。

if結構的條件下測試@user不是零,而不是在if條件中調用authenticate方法。所以改變:

@user = Refinery::User.find_by_id(current_user.id) 
if [email protected]? 
    current_user = Refinery::User.authenticate(@user.username, params[:user][:current_password]) 
. 
. 
. 

@user = Refinery::User.find_by_id(current_user.id) 
current_user = Refinery::User.authenticate(@user.username, params[:user][:current_password]) 
+1

這並沒有解決他得到的錯誤。 'authenticate'仍然是未定義的。 – Mischa

+0

你是對的。回答編輯。 – ahnbizcad