ruby-on-rails – Ruby on Rails,Devise gem.密码为空时如何删除当前密码?

现在我意识到这个话题已经被覆盖过很多次了.但是,似乎没有一种解决方案只有在数据库中的密码为空时才能使当前密码字段免除.

我目前在我的用户模型中需要密码,如:

def password_required?
  (authentications.empty? || !password.blank?) && super
end

然后我将更新功能复制到我的注册控制器中:

def update
  if resource.update_with_password(params[resource_name])
    set_flash_message :notice,:updated
    sign_in resource_name,resource,:bypass => true
    redirect_to after_update_path_for(resource)
  else
    clean_up_passwords(resource)
    render_with_scope :edit
  end
end

我只是不知道在编辑空白密码时如何确保设计不需要密码,我是否还需要从视图中删除current_password字段并执行此操作?

<% if current_user.password_required? %>
  <p><%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br />
  <%= f.password_field :current_password %></p>
<% end %>
<p><%= f.submit "Update" %></p>

任何建议都会很棒,因为我确信我忽视了一些东西,但我仍然是Rails的新手.谢谢!

解决方法

好的,所以我终于搞清楚了!

将以下内容添加到您的类RegistrationsController<设计:: RegistrationsController

def update
  if resource.update_with_password(params[resource_name])
    set_flash_message :notice,:bypass => true
    redirect_to after_update_path_for(resource)
  else
    clean_up_passwords(resource)
    render_with_scope :edit
  end
end

然后对您的用户模型进行以下操作:

def update_with_password(params={})
  current_password = params.delete(:current_password) if !params[:current_password].blank?

  if params[:password].blank?
    params.delete(:password)
    params.delete(:password_confirmation) if params[:password_confirmation].blank?
  end

  result = if has_no_password?  || valid_password?(current_password)
    update_attributes(params) 
  else
    self.errors.add(:current_password,current_password.blank? ? :blank : :invalid)
    self.attributes = params
    false
  end

  clean_up_passwords
  result
end

def has_no_password?
  self.encrypted_password.blank?
end

我唯一感到困惑的是在编辑视图中:

<% if !current_user.has_no_password? %>

我把它包裹起来如果,我原本以为它会是:

<% if current_user.has_no_password? %>

如果有人能看到任何改进我的代码或更高效的方式让我知道!

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...