在从rails控制台保存更新的密码记录时遇到麻烦



我正在编写一个简单的应用程序,并且在从rails控制台更新用户密码时遇到了一些困难。我是RoR(和Ruby)的新手。我肯定漏掉了一些简单的东西。我已经包含了我的模型以及我从Terminal得到的输出。

admin_users。rb模型

    require 'digest/sha1'
class AdminUser < ActiveRecord::Base
  attr_accessor :password
  EMAIL_REGEX = /^[A-Z0-9._%+-]+@[A-Z0-9.-].[A-Z]{2,4}$/i
  def self.authenticate(username="", password="")
    user = AdminUser.find_by_username(username)
    if user && user.password_match?(password)
        return user
    else
        return false
    end
  end
  def password_match?(password="")
    hashed_password == AdminUser.hash_with_salt(password, salt)
  end
  validates :first_name, :presence => true, :length => { :maximum => 25 }
  validates :last_name, :presence => true, :length => { :maximum => 50 }
  validates :username, :presence => true, :length => { :within => 8..25 }, :uniqueness => true
  validates :email, :presence => true, :length => { :maximum => 100 }, :uniqueness => true, :format=> EMAIL_REGEX, :confirmation => true
  # only on create ,so other attributes of this user can be changed
  validates_length_of :password, :within => 8..25, :on => :create
  before_save :create_hashed_password
  after_save :clear_password
  # scope :named, lambda {|first, last| where (:first_name => first, :last_name => last)}
  attr_protected :hashed_password, :salt
  def self.make_salt(username="")
    Digest::SHA1.hexdigest("Use #{username} with #{Time.now} to make salt")
  end
  def self.hash_with_salt(password="", salt="")
    Digest::SHA1.hexdigest("Put #{salt} on #{password}")
  end
  private
  def create_hashed_password
    # Whenever :password has a value, hashing is needed
    unless password.blank?
      #always use "self" when assigning values
      self.salt = AdminUser.make_salt(username) if salt.blank?
      self.hashed_password = AdminUser.hash_with_salt(password, salt)
    end
  end
  def clear_password
    # for security reasons and because hasing is not needed
    self.password = nil
  end
end

终端 -

user = AdminUser.find(1)
user.password = ('secretpassword')
user.save

然后终端给我这个…

    (0.1ms)  BEGIN
  AdminUser Exists (0.4ms)  SELECT 1 AS one FROM `admin_users` WHERE (`admin_users`.`username` = BINARY 'benlinus' AND `admin_users`.`id` != 1) LIMIT 1
  AdminUser Exists (0.2ms)  SELECT 1 AS one FROM `admin_users` WHERE (`admin_users`.`email` = BINARY 'email.email@me.com' AND `admin_users`.`id` != 1) LIMIT 1
   (0.1ms)  ROLLBACK
 => false 
2.0.0-p195 :018 > user.save
   (0.1ms)  BEGIN
  AdminUser Exists (0.3ms)  SELECT 1 AS one FROM `admin_users` WHERE (`admin_users`.`username` = BINARY 'benlinus' AND `admin_users`.`id` != 1) LIMIT 1
  AdminUser Exists (0.2ms)  SELECT 1 AS one FROM `admin_users` WHERE (`admin_users`.`email` = BINARY 'email.email@me.com' AND `admin_users`.`id` != 1) LIMIT 1
   (0.1ms)  

我不知道挂在哪里。在我的验证中似乎没有出现错误,所以我有点困惑。

看起来您对姓名和电子邮件地址进行了唯一性验证。已经有相同姓名或电子邮件地址的记录。使用不同的名称和电子邮件地址更新其他记录,您应该可以

相关内容

最新更新