Ruby on Rails教程:如何在不确认密码的情况下编辑用户信息

我一直在研究Michael Hartl的Ruby on Rails教程。 目前,为了编辑任何用户属性,用户必须确认其密码。 有没有办法更新用户属性而不必这样做?

我的表单看起来像这样:

 

"

users_controller.rb中的更新定义如下所示:

 def update if @user.update_attributes(params[:user]) flash[:success] = "Edit Successful." redirect_to @user else @title = "Edit user" render 'edit' end end 

目前,update_attributes操作失败。

谢谢!

在您的User模型上,您可能有以下内容:

 validates_presence_of :password_confirmation 

添加if子句如下,这样它只检查密码实际更改时的确认:

 validates_presence_of :password_confirmation, :if => :password_changed? 

要稍微改进Dylan的答案,你需要定义那个给你错误的password_changed方法。 我使用了不同的名称,因为我不在乎密码是否已更改。

  validates :password, :presence => true, :confirmation => true, :length => { :within => 6..40 }, :unless => :already_has_password? private def already_has_password? !self.encrypted_password.blank? end 

如果您使用bcrypt加密密码,这里是在Rails 4上为我工作的代码

 #--Code for User method validates :password, presence: true, confirmation: true, :unless => :already_has_password? # private def already_has_password? !self.password_digest.blank? end