2012-08-05 23 views
1

我是一位Rails新手,剛剛完成Michael Hartl的Leils教程。真是個好人!Michael Hartl的sample_app用戶編輯current_password編輯

我最近五個小時的生活目標是強制用戶在用戶編輯頁面輸入他們的舊密碼作爲密碼更新過程的一部分。

這就是我所得到的;

我已將此字段添加到(sample_app)edit.html.erb頁面。

<%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br /> 
    <%= f.password_field :current_password %> 

我也更新user.rb與「current_password」如下

class User < ActiveRecord::Base 
attr_accessible :name, :email, :current_password, :password, :password_confirmation, 

這是當前服務器端錯誤mesage我得到(我「一派錯誤消息!一百年次)

"ActiveRecord::UnknownAttributeError in UsersController#update 

unknown attribute: current_password 
Rails.root: /Users/nicolemcnight/rails_projects/sample_app 

Application Trace | Framework Trace | Full Trace 
app/controllers/users_controller.rb:55:in `update'" 

顯然有什麼不對的users_controller,特別是‘高清更新’目前看起來是這樣的;

def update 
    if @user.update_attributes(params[:user]) 
    flash[:success] = "Profile updated" 
    sign_in @user 
    redirect_to @user 
    else 
    render 'edit' 
    end 
end 

我的問題是什麼改變,我需要做出「高清更新」以包括current_password屬性!?還有我需要做的其他更新?

基本上,我想要做的就是強制用戶在用戶編輯頁面輸入(並確認)新密碼之前確認其舊密碼。

我在哪裏錯了?

任何幫助表示讚賞!

,這裏是我的github

https://github.com/mwcahn/sample_app

謝謝!

回答

0

您需要將current_password添加到attr_accessor,而不是attr_accessible - 它們是兩個完全不同的東西。因此,

attr_accessor :current_password 
attr_accessible :name, :email, ... etc 

current_password現在是用戶模型的有效屬性。

也就是說,您仍然需要向模型中添加代碼,以使其在更新之前執行密碼檢查。類似於

before_update :confirm_passwords 

def confirm_passwords 
    if current_password != password 
     errors.add(:current_password, "Does not match password") 
    end 
end 

請注意,上述代碼僅用於演示目的。數據庫中的實際密碼值是/應加密。所以你不能只做current_password!=密碼。您需要將您的current_password轉換爲您在密碼上使用的相同加密並比較該值。如果您使用Rails的默認has_secure_password這應該工作(但未經測試) -

def confirm_passwords 
    errors.add(:current_password, "Does not match password") unless self.authenticate(current_password) 
end 
+0

::加載ActiveModel :: MassAssignmentSecurity中的錯誤UsersController#更新 不能大規模指派保護的屬性:current_password – mwcahn 2012-08-05 08:58:28

+0

如果你得到的質量分配錯誤,添加:current_password到attr_accessible爲好。與@ user1559108寫的相反,你不應該在你的數據庫中添加一個current_password字段。您已經保存了用戶的密碼。編寫attr_accessor:current_password將創建一個不受數據庫支持的current_password屬性。沒有理由爲此創建數據庫列,這沒有任何意義。 – 2012-08-05 14:21:42

+0

好的,我銷燬了(rails破壞)current_password字段的添加。我添加了before_update(之前沒有見過)。現在沒有錯誤消息,但沒有任何錯誤消息:(我可以輸入任何我想要的current_password字段。我只是將所有內容都推送到我的github github.com/mwcahn。感謝您的幫助!我感受到了進步! – mwcahn 2012-08-05 18:24:49

-1

還有一個檢查:確保你做的數據庫遷移
軌產生遷移add_current_password_to_user current_password:字符串
耙分貝:遷移
萬一您忘記了。

+0

謝謝你們!兩者都有。試圖找出如何發佈新的錯誤信息到這個討論中。不確定在評論中做到這一點。或編輯我原來的問題。 – mwcahn 2012-08-05 08:38:49

+0

ActiveModel :: MassAssignmentSecurity :: UsersController中的錯誤#更新 無法批量分配受保護的屬性:current_password – mwcahn 2012-08-05 08:55:49

+0

嗯,使它attr_accessible應該擺脫它。 attr_accessor顯式禁止批量分配。我懷疑你的第一個錯誤是因爲你沒有遷移。你能證實這一點嗎? – av501 2012-08-05 09:46:41