Ruby on Rails,需要旧密码才能更改密码

时间:2014-11-26 19:56:24

标签: ruby-on-rails railstutorial.org

我使用gem'bcrypt'在rails中实现了一个用户身份验证系统;我想在编辑表单中插入一个当前密码字段来更改密码。 怎么办呢?

class User < ActiveRecord::Base
  before_save { self.email = email.downcase}
  before_create :create_remember_token
 
  #Associations
  has_one :profile
  has_many :posts

  #validations
  validates :name, presence: true, length:  {maximum: 50}
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, format:  {with: VALID_EMAIL_REGEX}, uniqueness: {case_sensitive: false}
  
  has_secure_password
  validates :password, length: {minimum: 6}
  
  def User.new_remember_token
    SecureRandom.urlsafe_base64
  end
  
  def User.digest(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

  private 
    def create_remember_token
      self.remember_token = User.digest(User.new_remember_token)
    end
  
end

<% provide(:title, "Edit user") %>
<h1>Update your profile</h1>

<div class="row">
  <div class="span6 offset3">
    <%= form_for(@user) do |f| %>
      <%= render 'shared/error_messages' %>

      <%= f.label :name %>
      <%= f.text_field :name %>

      <%= f.label :email %>
      <%= f.text_field :email %>

      <%= f.label :password %>
      <%= f.password_field :password %>

      <%= f.label :password_confirmation, "Confirm Password" %>
      <%= f.password_field :password_confirmation %>



      <%= f.submit "Save changes", class: "btn btn-large btn-primary" %>
    <% end %>

  </div>
</div>

谢谢

1 个答案:

答案 0 :(得分:0)

在您的视图文件中:

  <%= f.label :current_password %>
  <%= f.password_field :current_password %>

还要确保允许控制器中的current_password参数。

我假设current_password attr已经由has_secured_pa​​ssword定义。