0

我正在编写一个简单的应用程序,并且在从 rails 控制台更新用户密码时遇到了一些困难。我对 RoR(和 Ruby)非常陌生。我确定我缺少一些简单的东西。我已经包含了我的模型以及从终端获得的输出。

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)  

我不确定挂断在哪里。我的验证似乎没有出错,所以我有点困惑。

4

1 回答 1

1

看起来您对姓名和电子邮件地址进行了唯一性验证。已经存在具有相同名称或电子邮件地址的记录。用不同的姓名和电子邮件地址更新另一条记录,你应该没问题

于 2013-06-19T03:29:08.087 回答