【发布时间】:2015-03-15 10:51:48
【问题描述】:
在我的 Rails 4.0.9 应用程序中,使用 BCrypt 3.1.7 和 Clearance 1.4.2 进行身份验证,更新用户信息时返回错误。尽管没有输入新密码或密码确认,但我收到错误“密码不能为空”。
我在 SO 和谷歌上搜索过,但我发现没有一个解决方案适合我。大多数是针对早期版本的 Rails,现在可能已经过时了,而其他的并不真正适合我的确切情况(可能是因为我只是在做一些愚蠢的事情)。
我可以从编辑表单中删除密码和密码确认字段,但我确实希望用户能够更新他们的密码,同时更新他们的姓名或电子邮件地址,如果他们愿意的话。
'has_secure_password' 应该只在创建时验证,但似乎也在更新时验证。为了解决这个问题,我禁用了我的用户模型对密码和密码确认的验证,并简单地使用“has_secure_password”来验证这些参数。你能明白为什么我会收到验证错误吗? Clearance gem 是否覆盖了 has_secure_passwords 的默认行为,或以任何方式影响验证?
用户模型
class User < ActiveRecord::Base
include Clearance::User
belongs_to :studio
has_one :public_user
before_save { self.email = email.downcase }
before_create :create_remember_token
after_create :make_public_user
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
validates :email, presence: true,
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
has_secure_password
# validates :password, length: { minimum: 6, on: :create }
# validates :password_confirmation, presence: { on: :create }
...
用户控制器
...
def edit
end
def update
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, :password_digest)
end
...
编辑表单(实际上是“_fields.html.erb”部分)
<%= render 'shared/error_messages', object: f.object %>
<div class="control-group">
<%= f.label :name, class: "control-label" %>
<div class="controls">
<%= f.text_field :name %>
</div>
</div>
<div class="control-group">
<%= f.label :email, class: "control-label" %>
<div class="controls">
<%= f.text_field :email %>
</div>
</div>
<div class="control-group">
<%= f.label :password, class: "control-label" %>
<div class="controls">
<%= f.password_field :password, placeholder: 'Enter new password if changing' %>
</div>
</div>
<div class="control-group">
<%= f.label :password_confirmation, "Confirmation", class: "control-label" %>
<div class="controls">
<%= f.password_field :password_confirmation, placeholder: 'Confirm your new password if changing' %>
</div>
</div>
传递给控制器的参数
Parameters: {"utf8"=>"✓", "authenticity_token"=>"[FILTERED]", "user"=>{"name"=>"Ransom Kshlerin III", "email"=>"example-1@samplestudio.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Save changes", "id"=>"4"}
编辑:
当我禁用“has_secure_password”时,我仍然收到验证错误,这让我相信 Clearance 的验证正在返回错误。我认为我需要覆盖 Clearance 的密码验证,但仅限于更新用户时。我该怎么办?
编辑 2:
我将采取完全不同的方法。我将提供一个用于重置密码的链接,而不是允许直接在此表单上重置密码,该链接将向用户发送一封电子邮件,其中包含重置密码的链接。
【问题讨论】:
标签: validation ruby-on-rails-4