2011-10-27 34 views
6

我想創建一個用戶(管理員),並且想要使用控制檯(不需要用戶註冊模型)。我使用RailsCasts的解決方案(http://railscasts.com/episodes/270-authentication-in-rails-3-1)。 但我有一個問題:當我在控制檯中執行User.create(...,:password =>「pass」)時,我的密碼存儲在數據庫中而沒有encription(如「pass」)。而且我無法使用我的數據登錄。Rails 3.1。使用安全密碼在控制檯中創建一個用戶

如何從控制檯創建用戶? :)

回答

21

直接從Rails的API

# Schema: User(name:string, password_digest:string) 
class User < ActiveRecord::Base 
    has_secure_password 
end 

user = User.new(:name => "david", :password => "", :password_confirmation => "nomatch") 
user.save              # => false, password required 
user.password = "mUc3m00RsqyRe" 
user.save              # => false, confirmation doesn't match 
user.password_confirmation = "mUc3m00RsqyRe" 
user.save              # => true 
user.authenticate("notright")         # => false 
user.authenticate("mUc3m00RsqyRe")        # => user 

您需要在您的哈希:password_confirmation => "pass

對,所以看看has_secure_password你想要執行BCrypt::Password.create(unencrypted_password)來獲得它。您需要使用bcrypt-ruby寶石來完成上述操作。

+0

謝謝!我忘了BCrypt,它沒有密碼確認太好:) –

+0

真棒,很高興聽到它=) –

相關問題