1

我是刚完成 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, 

这是我收到的当前服务器端错误消息(我已经“用谷歌搜索了错误消息!一百次”)

"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”,目前看起来像这样;

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

谢谢!

4

2 回答 2

0

您需要将 :current_password 添加到 attr_accessor,而不是 attr_accessible - 它们是两个非常不同的东西。就这样

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

current_password 现在是 User 模型的有效属性。

也就是说,您仍然需要向模型添加代码,以使其在更新前进行密码检查。就像是

before_update :confirm_passwords

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

请注意,以上代码仅用于演示目的。数据库中的实际密码值是/应该加密的。所以你不能只做 current_password != password。您需要使用您在密码上使用的相同加密转换您的 current_password 并比较该值。如果您使用 Rails 的默认 has_secure_password 这应该可以工作(但未经测试) -

def confirm_passwords
    errors.add(:current_password, "Does not match password") unless self.authenticate(current_password)
end
于 2012-08-05T07:50:11.080 回答
-1

再检查一项:确保您对数据库进行了迁移
rails generate migration add_current_password_to_user current_password:string
rake db:migrate
以防您忘记了这一点。

于 2012-08-05T08:05:57.437 回答