2013-01-16 28 views
0

我有我使用內置的用戶模型的Rails的has_secure_password(基於Rails tutorial Book):將current_password字段添加到以下更改密碼視圖?

schema.rb:

create_table "users", :force => true do |t| 
    t.string "password_digest" 
end 

user.rb:

class User < ActiveRecord::Base 
    attr_accessible :name, :email, :avatar, :password, :password_confirmation, :provider, :uid 

    has_secure_password 

    validates :password, presence: true, length: { minimum: 6 } 
    validates :password_confirmation, presence: true 

我有這樣的看法uses/password_edit.html.erb

<%= f.label :password %> 
<%= f.password_field :password, "New Password" %> 

<%= f.label :password_confirmation, "Retype Password" %> 
<%= f.password_field :password_confirmation %> 

現在,我想補充一個在頂部:current_password場。問題是數據庫只有一個password_digest列。

所以,我在這裏有點迷路。我甚至不知道當current_password不正確時如何使表格發出錯誤。

有什麼建議嗎?

編輯:

users_controller.html.erb:

高清更新 OLD_PASSWORD =參數[:current_password]

if authenticated = User.authenticate(old_password) 
    if params[:user][:password].blank? && params[:user][:password_confirmation].blank? 
    # Use old password if none indicated 
    params[:user][:password] = old_password 
    params[:user][:password_confirmation] = old_password 
    end 
end 

@user = User.find(params[:id]) 
@user.errors.add(:base, "Invalid password") unless authenticated 
@user.updating_password = true if params[:form_name] == "edit_password" 
if authenticated && @user.update_attributes(params[:user]) 
    flash[:success] = "Profile updated" 
    sign_in @user 
    redirect_to @user 
else 
    if params[:form_name] == "edit_password" 
    render 'edit_password' 
    else 
    render 'edit' 
    end 
end 
@user.updating_password = nil 

+0

你可以添加你的視圖看起來像現在一樣,並修改控制器編輯格式? – Geoff

回答

1

我做了類似的事情最近。我在,這不是與模型相關視圖中添加的輸入,然後我的控制器是這樣的:

def update 
    old_password = params[:current_password] 

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

    if authenticated = @user.authenticate(old_password) 
    if params[:user][:password].blank? && params[:user][:password_confirmation].blank? 
     # Use old password if none indicated 
     params[:user][:password] = old_password 
     params[:user][:password_confirmation] = old_password 
    end 
    end 

    @user.errors.add(:base, "Invalid password") unless authenticated 

    if authenticated && @user.update_attributes(params[:user]) 
    ... 
end 

這似乎爲我工作。我希望它能幫助你。

+0

糟糕,如果用戶未通過身份驗證,則會丟棄用戶的任何更改。我可以對其進行修改,以包括如果您希望或將其留作提問者的練習。 – Geoff

+0

感謝您的回答。你能包括嗎? – alexchenco

+1

當然可以。我想你可以在最後一行'@ user.assign_attributes(params [:user])'和'@ user.valid?'之前加上以下兩條語句,然後你可以將最後一行改爲'@ user.save'。 – Geoff

相關問題