尝试更改密码时设计警告:无法批量分配受保护的属性:current_password

时间:2011-08-11 18:39:30

标签: ruby-on-rails ruby-on-rails-3 devise

使用rails 3 + devise,我希望用户能够更改密码:

这是日志输出:

Started POST "/settings/password/update" for 127.0.0.1 at 2011-08-11 11:37:05 -0700
  Processing by SettingsController#password_update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"QBZP/h0Xg1SOBWh0+JwzFRyC8X7pE50mx1CgeS6+iNY=", "user"=>{"current_password"=>"[FILTERED]", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Change my password"}
  User Load (0.6ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 3 LIMIT 1
  SQL (0.2ms)  BEGIN
WARNING: Can't mass-assign protected attributes: current_password
  AREL (0.7ms)  UPDATE "users" SET "encrypted_password" = '$2a$10$cjq9eWB41aqeukarMzyciO4adXB3g.gCSwP6OouV0HT9HZI3IVIa6', "updated_at" = '2011-08-11 18:37:06.326258' WHERE "users"."id" = 3
[paperclip] Saving attachments.
  SQL (25.7ms)  COMMIT
Redirected to http://localhost:3000/settings/account
Completed 302 Found in 556ms

这是password_update的控制器方法:

  def password_update

    @user = current_user

    if @user.update_attributes(params[:user])
      flash[:notice] = 'Password Updated'
      redirect_to '/settings/account'
    else
      flash[:notice] = 'Error'
      redirect_to '/settings/password'
    end

  end

为什么会发生这种情况?我不是要设置current_password但是根据设计你需要通过它来更新密码,对吧?感谢

2 个答案:

答案 0 :(得分:3)

我更喜欢在用户模型上覆盖update_without_password方法

def update_without_password(params={})
  params.delete(:current_password)
  super(params)
end

答案 1 :(得分:2)

attr_accessible :current_password添加到您的用户模型。