2011-06-18 8 views
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 
+0

私が見ている唯一のエラーメッセージは、私がIRBにuser.saveを入力すると "偽"です。自分の投稿を編集してUserモデルのソースコードを追加しました。 – Kvass

+0

代わりに 'user.save!'を使って、どんな例外がスローされるのかを見てください。 'user.valid?'もチェックし、falseの場合は 'user.errors'です。 – Jonah

答えて

0

お試しください!例外があなたに通知するものを参照してください

+0

そのおかげで問題は解決しました^。^ – Kvass

関連する問題