【问题标题】:Rails Password ChangeRails 密码更改
【发布时间】:2013-09-17 08:54:55
【问题描述】:

我将首先告诉您我希望如何设置我的设置页面。

我希望用户能够在不需要密码的情况下更改他们的设置,这就是现在使用它作为用户模型的设置方式

validates :password, presence: true, length: { minimum: 6 }, :on => :create
validates :password_confirmation, presence: true, :on => :update, :unless => lambda{ |user| user.password.blank? }

这样用户就可以在不需要密码的情况下更改所有设置(我知道有些人可能会对此皱眉头)。但是我希望用户能够像这样在页面上更改他们的密码......用户单击更改密码,弹出一个模式,用户必须提供他们当前的密码,然后是新密码并确认新密码。 (我知道如何做模态,我只想知道如何重置密码)。

这有意义吗??我相信 Pinterest 的做法是一个很好的例子(尽管我认为他们使用 Python)

【问题讨论】:

  • 你在用设计吗?
  • 不,我是从零开始的

标签: ruby-on-rails passwords pinterest


【解决方案1】:

我的建议是使用表单对象:

app/forms/change_password_form.rb

class ChangePasswordForm
  extend ActiveModel::Naming
  include ActiveModel::Conversion
  include ActiveModel::Validations

  # Add all validations you need
  validates_presence_of :old_password, :password, :password_confirmation
  validates_confirmation_of :password
  validate :verify_old_password

  attr_accessor :old_password, :password, :password_confirmation

  def initialize(user)
    @user = user
  end

  def submit(params)
    self.old_password = params[:old_pasword]
    self.password = params[:password]
    self.password_confirmation = params[:password_confirmation]

    if valid?
      @user.password = password
      @user.password_confirmation = password_confirmation
      @user.save!
      true
    else
      false
    end
  end

  def verify_old_password
    self.errors << "Not valid" if @user.password != password
  end

  # This method is required
  def persisted?
    false
  end
end

在控制器中初始化表单对象 @pass_form = ChangePasswordForm.new(current_user) 并在您的模式中使用该对象:form_for @pass_form... 并添加 old_passwordpasswordpassword_confirmation 字段。

最后,例如在更新操作中:

@pass_form = ChangePasswordForm.new(current_user)

if @pass_form.submit(params[:change_password_form])
  redirect_to some_path
else
  render 'new'
end

我没有测试过这段代码,但你明白了。看看这个Railscasts

【讨论】:

  • 我是否需要为此向用户数据库添加新列?
  • 不,您仍在使用您的User 模型。如果你看到@userUser 的一个实例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-15
  • 1970-01-01
  • 2019-05-09
  • 1970-01-01
  • 2017-10-05
  • 2015-07-29
  • 2019-12-03
相关资源
最近更新 更多