所以我使用 Sorcery Gem 来处理我的Rails应用程序中的身份验证(通过Mongoid使用MongoDB作为数据库)和我的用户模型看起来像这样:
class User
include Mongoid::Document
attr_accessible :username, :email, :password, :password_confirmation
authenticates_with_sorcery!
field :username, :type => String
field :email, :type => String
field :username, :type => String
field :password, :type => String
field :password_confirmation, :type => String
validates_confirmation_of :password
validates_presence_of :password, :on => :create
validates_presence_of :username
validates_uniqueness_of :username
validates_presence_of :email
validates_uniqueness_of :email
end
通过“新用户视图”(本例)创建新用户:
<%= form_for @user do |f| %>
<% if @user.errors.any? %>
<div class="error_messages">
<h2>Form is invalid</h2>
<ul>
<% for message in @user.errors.full_messages %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :username %>
<%= f.text_field :username %>
</div>
<div class="field">
<%= f.label :email %>
<%= f.text_field :email %>
</div>
<div class="field">
<%= f.label :password %>
<%= f.password_field :password %>
</div>
<div class="field">
<%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation %>
</div>
<div class="actions"><%= f.submit %></div>
<% end %>
在数据库中生成如下记录:
1.9.3-p286 :002 > u = User.first
=> #<User _id: 507e6dd961ef51512d000004, _type: nil, username: "Jmlevick", email: "Jmlevick@Jmlevick.com", crypted_password: "$2a$10$yoRzXIu0a2uRRuu9z5MbD.TQQ2upawMC0DGuC/njlQjqzHwdhVWTm", salt: "xwCVQuCNWb9o3fKgvffa", remember_me_token: nil, remember_me_token_expires_at: nil, reset_password_token: nil, reset_password_token_expires_at: nil, reset_password_email_sent_at: nil, password: nil, password_confirmation: "MySecretPassword">
所以用户已保存,我可以使用凭据进行访问,但正如您所看到的,记录中有两个奇怪的内容:1)密码设置为“nil”(但是实际上数据库保存了实际的密码并将其隐藏起来,所以我很好用它)和:password_confirmation 字段显示密码(为了安全起见必须加密) )!
为什么会这样?我该如何解决?我需要一个密码确认字段!
答案 0 :(得分:1)
我认为您只需要在password_confirmation
课程中不包含User
字段 - Mongoid应该查找password_confirmation
字段,因为您设置了validate_confirmation_of :password
,所以我认为你不需要明确地设置它。