Ruby on Rails 4:has_secure_password在创建新用户时不要求密码确认

时间:2014-07-14 20:06:15

标签: authentication ruby-on-rails-4 passwords activemodel

我目前正在使用RoR4编写应用程序,但我在验证时遇到问题。即使我已将has_secure_password添加到用户模型,我似乎仍然可以创建新用户而无需提供密码确认。

2.1.2 :012 > me = User.create(:institution_id => 1, :email => "me@myschool.edu", :password => "mypassword")
(0.1ms)  BEGIN
User Exists (0.3ms)  SELECT  1 AS one FROM `users`  WHERE `users`.`email` = BINARY  'me@myschool.edu' LIMIT 1
SQL (0.2ms)  INSERT INTO `users` (`created_at`, `email`, `institution_id`, `password_digest`, `updated_at`) VALUES ('2014-07-14 20:02:34', 'me@myschool.edu', 1, '$2a$10$sD2N.2nxhYO7egzzWxfF5.cdIZ4ds41.sU93Ja3E9Q0qAOaABdZb6', '2014-07-14 20:02:34')
(8.2ms)  COMMIT
=> #<User id: 5, institution_id: 1, first_name: nil, last_name: nil, email: "me@myschool.edu", blurb: nil, facebook_link: nil, facebook_token: nil, password_digest: "$2a$10$sD2N.2nxhYO7egzzWxfF5.cdIZ4ds41.sU93Ja3E9Q0...", api_key: nil, active: false, created_at: "2014-07-14 20:02:34", updated_at: "2014-07-14 20:02:34", authentication_token: nil> 

为什么会这样? has_secure_password不应该总是需要密码确认吗?

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

确保你遵循这些事情:

gem 'bcrypt'添加到gem文件。

下一步:

拥有password_digest属性

下一步:

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
User.find_by(name: 'david').try(:authenticate, 'notright')      # => false
User.find_by(name: 'david').try(:authenticate, 'mUc3m00RsqyRe') # => user