我的用户模型中有一个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,但它没有回答我的具体问题。
更新 用户模型片段:
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