Michael Hartl的sample_app用户编辑current_password编辑

时间:2012-08-05 07:38:23

标签: ruby-on-rails ruby-on-rails-3 change-password

我是一个刚刚完成Michael Hartl的学习Rails教程的Rails新手。真是个好人!

我过去五个小时的人生目标是强制用户在“用户编辑”页面中输入旧密码作为密码更新过程的一部分。

这是我已经得到的;

我已将此字段添加到(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 %>

我还使用'current_password'更新了user.rb,如下所示

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

这是我正在收到的当前服务器端错误消息(我已经用Google搜索了错误消息!一百次')

"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'"

显然user_controller有问题,特别是'def update',目前看起来像这样;

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

我的问题是,我需要对“def update”进行哪些修改才能包含current_password属性!?还有我需要做的其他任何更新吗?

基本上我想做的就是强迫用户在用户编辑页面输入(并确认)新密码之前确认他们的旧密码。

我在哪里错了?

任何帮助表示赞赏!

这是我的github

https://github.com/mwcahn/sample_app

谢谢!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:-1)

再检查一次:确保您已完成数据库的迁移
rails生成迁移add_current_password_to_user current_password:string
rake db:migrate
如果你忘记了。

相关问题