【发布时间】:2023-04-02 13:04:04
【问题描述】:
我的用户模型中有一个validates_confirmation_of :password。问题是,当创建评论以更新用户帐户的某些属性时,我也会运行 @comment.user.save!。
创建评论 Validation failed: Password confirmation can't be blank 时出现错误。我无法将:on => "save" 添加到我的验证中,因为我的comments 控制器也在调用保存函数。
我已阅读此主题 Rails model validation on create and update only,但它没有回答我的具体问题。
更新 用户模型sn-p:
class User < ActiveRecord::Base
attr_accessor :password
# validations
validates_presence_of :username
validates_length_of :username, :within => 6..25
validates_uniqueness_of :username
validates_presence_of :email
validates_length_of :email, :maximum => 100
validates_format_of :email, :with => EMAIL_REGEX
validates_confirmation_of :password, :if => :password_changed?
validates_presence_of :password_confirmation
validates_length_of :password, :within => 4..25, :on => :create
before_save :create_hashed_password
after_save :clear_password
private
def clear_password
self.password = nil
end
end
【问题讨论】:
标签: ruby-on-rails-3 validation password-confirmation