我已经在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
答案 0 :(得分:2)
看看ActiveModel::Dirty
。要仅在activestatus
从active
更改为inactive
时运行验证,只需在自定义验证方法中添加一行:
def check_on_update
return unless activestatus_changed?(from: 'active', to: 'inactive')
# your validation code
end
答案 1 :(得分:0)
您可以使用ActiveModel :: Dirty
if activestatus_was == 'active' && activestatus == 'inactive'
# validation logic goes here
end
更多信息:https://api.rubyonrails.org/classes/ActiveModel/Dirty.html
希望有帮助!