首页 > 解决方案 > Rails 仅在特定字段值更改时更新验证

问题描述

我在 rails 模型中编写了一个自定义验证函数。我想检查验证是否仅更改了一个字段(在我的示例中,字段“activestatus”从“active”更改为“inactive”)。怎么做?

class Normaluser < ApplicationRecord
   validate :check_on_update, :on => :update
   validate :check_on_status_change :"***what to write here?***"
   private

   def check_on_update
    if is_cyclic?
        puts "hierarchy is cyclic"
        errors.add(:pid,'it is cyclic')

    elsif(get_height(id)+getDepth>=2)
        puts "height limit exceeded"
        errors.add(:pid,'height limit exceeded')
    elsif count_children>=4
        errors.add(:pid,'children limit exceeded')
    end
    puts "all is fine at update"
end 

标签: ruby-on-railsrubyvalidationactiverecord

解决方案


看看ActiveModel::Dirtyactivestatus仅在更改activeinactive仅向自定义验证方法添加一行时才运行验证:

def check_on_update
  return unless activestatus_changed?(from: 'active', to: 'inactive')

  # your validation code
end

推荐阅读