Rails仅在用户创建或更新时验证

Ton*_*ate 4 validation password-confirmation ruby-on-rails-3

validates_confirmation_of :password我的用户模型中有一个.问题是我还在@comment.user.save!创建注释时运行以更新用户帐户的某些属性.

创建评论时出错Validation failed: Password confirmation can't be blank.我无法添加:on => "save"到我的验证,因为我的comments控制器也调用了保存功能.

我在创建和更新时已经阅读了这个线程Rails模型验证,但它没有回答我的具体问题.

更新 用户模型代码段:

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
Run Code Online (Sandbox Code Playgroud)

Mar*_*her 6

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


编辑: 我建议类似于:

class Comment < ActiveRecord::Base
  after_save :rank_user

  def rank_user
    # calculate rank
    user.update_attribute(:rank, rank)
  end
end
Run Code Online (Sandbox Code Playgroud)

这种方法的好处:

  1. 您的控制器和模型将是干净的,rank_user将自动调用,无需显式调用@comment.user.save!.
  2. 根据update_attribute文档,将跳过验证,然后不会导致密码确认错误.


cic*_*oon 6

根据此validates_confirmation_of,如果password_confirmation字段为nil,则模型应该有效.你把它存放到DDBB吗?或者验证可能有问题,您可以在此处粘贴用户模型吗?

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

validates_presence_of :password_confirmation, if: -> { password.present? }
validates_confirmation_of :password, if: -> { password.present? }
Run Code Online (Sandbox Code Playgroud)