通过railstutorial.org工作。目前在Update Profile页面的一部分。将Password
和Password Confirmation
字段留空时,只会出现Password is too short
错误,但在教程屏幕截图中显示Password confirmation can't be blank
消息。但是,当Password
字段填充且Password Confirmation
字段留空时,它会显示。
edit.html.erb
:
<% provide(:title, "Edit user") %>
<h1>Update your profile</h1>
<div class="row">
<div class="span6 offset3">
<%= form_for(@user) do |f| %>
<%= render 'shared/error_messages' %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :email %>
<%= f.text_field :email %>
<%= f.label :password %>
<%= f.password_field :password %>
<%= f.label :password_confirmation, "Confirm Password" %>
<%= f.password_field :password_confirmation %>
<%= f.submit "Save changes", class: "btn btn-large btn-primary" %>
<% end %>
<%= gravatar_for @user %>
<a href="http://gravatar.com/emails">change</a>
</div>
</div>
users_controller.rb
:
.
.
.
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
if @user.update_attributes(user_params)
flash[:success] = "Profile updated"
redirect_to @user
else
render 'edit'
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
.
.
.
user.rb
:
class User < ActiveRecord::Base
has_secure_password
before_save { self.email = email.downcase }
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(?:\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true,
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates :password, length: { minimum: 6 }
before_create :create_remember_token
def User.new_remember_token
SecureRandom.urlsafe_base64
end
def User.digest(token)
Digest::SHA1.hexdigest(token.to_s)
end
private
def create_remember_token
self.remember_token = User.digest(User.new_remember_token)
end
end
答案 0 :(得分:1)
您的User.rb
模型与MHartl uses at that point in the tutorial模型不同步。具体来说,请注意除了validates :password_confirmation, presence: true
之外,他还有一个明确的validates :password, length: { minimum: 6 }
。当你调用@ user.update_attributes时,它会命中这些验证器,在他的情况下,它们都会失败,而在你的User.rb模型中则没有存在验证器。
如果您填写了密码字段,则会点击has_secure_password
而不是模型中定义的验证器,这就是他们出现的原因。
答案 1 :(得分:0)
确保在控制器中的允许参数中包含密码和password_confirmation:
private
def user_params
params.required(:user).permit(:name, :email, password,:password_confirmation)
end
修改强>
正如对方已经指出你错过了password_confirmation
validates :password_confirmation, presence: true