【问题标题】:Rails validate only on user create or updateRails 仅在用户创建或更新时验证
【发布时间】: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


    【解决方案1】:

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


    编辑: 我建议类似于:

    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 documentation,将跳过验证,从而不会导致密码确认错误。

    【讨论】:

    • 我正在运行它,因为我正在更新 user.rank 属性。我可以在我的 cmets 控制器之外做类似的事情吗?
    【解决方案2】:

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

    无论哪种方式,您都可以尝试以下方法:

    validates_presence_of :password_confirmation, if: -> { password.present? }
    validates_confirmation_of :password, if: -> { password.present? }
    

    【讨论】:

    • 也许它失败的原因是因为我有一个validates_presence_of :password_confirmation?我补充说,因为如果用户将其留空,它不会检查它。另外,它说:password_changed? 是未定义的。我需要定义它吗?
    • 既然password是虚拟字段,那么password_changed方法呢?不生成。我编辑了我的答案来纠正这个问题,它应该可以工作。
    • 非常感谢。这正是我所缺少的。
    猜你喜欢
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 1970-01-01
    • 2021-07-13
    相关资源
    最近更新 更多