我的用户模型中有一个validates_confirmation_of :password
。问题是我也运行@comment.user.save!
当创建评论来更新用户帐户的一些属性。Rails仅在用户创建或更新时验证
创建评论Validation failed: Password confirmation can't be blank
时出现错误。我无法将:on => "save"
添加到我的验证中,因为我的comments
控制器也在调用保存功能。
我已阅读此主题Rails model validation on create and update only,但它不回答我的具体问题。
UPDATE 用户模型片段:
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
也许它失败的原因是因为我有'validates_presence_of:password_confirmation'?我补充说,因为如果用户将其留空,它不会检查它。另外,它说':password_changed?'是未定义的。我需要定义这个吗? –
由于密码是虚拟字段,因此密码方法password_changed?没有生成。我编辑我的答案来纠正这个问题,它应该工作。 – cicloon
非常感谢。这正是我所错过的。 –