使用 Ruby 1.9.3 和 bcrypt-ruby 3.0.1
我正在开发敏捷 Web 开发书中的 Depot 应用程序,并且在验证用户的当前密码以让他们更改密码时遇到问题。
我的用户模型:
class User < ActiveRecord::Base
validates :name, presence: true, uniqueness: true
attr_accessible :name, :password, :current_password, :password_confirmation
has_secure_password
after_destroy :ensure_an_admin_remains
private
def ensure_an_admin_remains
if User.count.zero?
raise "Can't delete last user"
end
end
end
我在用户控制器中的更新方法如下所示:
def update
@user = User.find(params[:id])
if @user.authenticate(params[:current_password])
params[:user].delete :current_password
respond_to do |format|
if @user.update_attributes(params[:user])
format.html { redirect_to users_url, notice: "User #{@user.name} was successfully updated." }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
else
redirect_to edit_user_path(@user), notice: "Current password is incorrect."
end
end
我的用户表单如下所示:
<%= form_for(@user) do |f| %>
<% if @user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>
<ul>
<% @user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<fieldset>
<legend>Enter User Details</legend>
<div>
<%= f.label :name %><br />
<%= f.text_field :name, size: 40 %>
</div>
<% if params[:action] == :edit %>
<div>
<label for="old_password">Old Password:</label>
<%= password_field_tag :current_password, params[:current_password]%>
</div>
<% end %>
<div>
<%= f.label :password, 'Password' %><br />
<%= f.password_field :password, size: 40 %>
</div>
<div>
<%= f.label :password_confirmation, 'Confirm' %>
<%= f.password_field :password_confirmation, size: 40%>
</div>
<div>
<%= f.submit %>
</div>
</fieldset>
<% end %>
问题似乎与@user.authenticate(params[:current_password])
线路有关。我很困惑,因为我认为身份验证在参数的范围内,也因为控制台上的这个方法确实通过了。