1
所以我遇到了一個驗證問題 - 我創建了一個驗證,以確保數據庫中的用戶不共享相同的電子郵件地址。然後我在數據庫中創建了一個用戶。之後,我說user = User.find(1)
返回了我剛創建的用戶。然後我想改變它的名字,所以我說user.name = "New Name"
,然後嘗試使用user.save
將它保存回數據庫。然而,這個命令不再工作(它會返回false),我認爲這與我的唯一性驗證測試有關。有人可以幫我解決這個問題嗎?Rails - 更新數據庫中的模型
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# name :string(255)
# email :string(255)
# created_at :datetime
# updated_at :datetime
#
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email, #says that the name and email attributes are publicly accessible to outside users.
:password, :password_confirmation #it also says that all attributes other than name and email are NOT publicly accessible.
#this protects against "mass assignment"
email_regex = /^[A-Za-z0-9._+-][email protected][A-Za-z0-9._-]+\.[A-Za-z0-9._-]+[A-Za-z]$/ #tests for valid email addresses.
validates :name, :presence => true,
:length => {:maximum => 50}
validates :email, :presence => true,
:format => {:with => email_regex},
:uniqueness => {:case_sensitive => false}
validates :password, :presence => true,
:length => {:maximum => 20, :minimum => 6},
:confirmation => true
before_save :encrypt_password
def has_password?(submitted_password)
#compare encrypted_password with the encrypted version of the submitted password.
encrypted_password == encrypt(submitted_password)
end
def self.authenticate(email, submitted_password)
user = find_by_email(email)
if (user && user.has_password?(submitted_password))
return user
else
return nil
end
end
private
def encrypt_password
if (new_record?) #true of object has not yet been saved to the database
self.salt = make_salt
end
self.encrypted_password = encrypt(password)
end
def encrypt(string)
secure_hash("#{salt}--#{string}")
end
def secure_hash(string)
Digest::SHA2.hexdigest(string) #uses cryptological hash function SHA2 from the Digest library to encrypt the string.
end
def make_salt
secure_hash("#{Time.now.utc}--#{password}")
end
end
我看到的唯一錯誤信息就是當我輸入user.save進入IRB時「false」。我編輯了我的帖子以包含用戶模型源代碼。 – Kvass
改用'user.save!'來查看拋出了什麼異常。同時檢查'user.valid?',如果這個錯誤'user.errors'。由於^^^解決了 – Jonah