4

我的用户模型中有一个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
4

2 回答 2

6

你究竟为什么要跑步@comment.user.save!?触摸(例如更新时间戳)和增加评论数可以通过内置机制完成。


编辑: 我建议类似于:

class Comment < ActiveRecord::Base
  after_save :rank_user

  def rank_user
    # calculate rank
    user.update_attribute(:rank, rank)
  end
end

这种方法的好处:

  1. 您的控制器和模型将是干净的,并且rank_user会自动调用,无需显式调用@comment.user.save!.
  2. 根据update_attribute文档,将跳过验证,然后不会导致密码确认错误。
于 2011-08-29T11:17:27.920 回答
6

根据这个validates_confirmation_of如果 password_confirmation 字段为 nil,模型应该是有效的。您是否将其存储到 DDBB?或者您的验证可能有问题,您可以在这里粘贴您的用户模型吗?

无论哪种方式,您都可以尝试这样的事情:

validates_presence_of :password_confirmation, if: -> { password.present? }
validates_confirmation_of :password, if: -> { password.present? }
于 2011-08-29T11:56:34.893 回答