【问题标题】:Adding a current_password field to the following change password view?将 current_password 字段添加到以下更改密码视图?
【发布时间】:2013-01-17 14:44:45
【问题描述】:

我有一个使用 Rails 的has_secure_password(基于Rails tutorial Book)构建的用户模型:

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 = params[: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

结束

【问题讨论】:

  • 您可以添加您的视图现在的样子并修复控制器编辑的格式吗?

标签: ruby-on-rails


【解决方案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

这似乎对我有用。希望对你有帮助。

【讨论】:

  • 糟糕,如果用户身份验证失败,这将丢弃用户所做的任何更改。如果您愿意,我可以修改它以包含它,或者将其作为提问者的练习。
  • 感谢您的回答。你能把它包括进去吗?
  • 当然。我认为您可以在最后一行 @user.assign_attributes(params[:user])@user.valid? 之前添加以下两个语句,然后您可以将最后一行更改为 @user.save
  • 抱歉,这与:current_password 字段有何关联?现在:password:current_password 字段正常(它们创建并确认新密码)。我只需要创建:current_password 字段。
  • 是的,对不起,我最初没有使用你的名字。
猜你喜欢
  • 1970-01-01
  • 2015-12-19
  • 2014-05-28
  • 2022-10-07
  • 1970-01-01
  • 2011-11-01
  • 2012-12-03
  • 2022-06-11
  • 1970-01-01
相关资源
最近更新 更多