Ruby on rails Rails仅在特定字段值更改时更新验证
我在rails模型中编写了一个自定义验证函数。我想检查是否只更改了一个字段(在我的示例中,字段“activestatus”从“active”更改为“inactive”)。怎么做Ruby on rails Rails仅在特定字段值更改时更新验证,ruby-on-rails,ruby,validation,activerecord,Ruby On Rails,Ruby,Validation,Activerecord,我在rails模型中编写了一个自定义验证函数。我想检查是否只更改了一个字段(在我的示例中,字段“activestatus”从“active”更改为“inactive”)。怎么做 class Normaluser < ApplicationRecord validate :check_on_update, :on => :update validate :check_on_status_change :"***what to write here?***" priva
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
class Normaluser:更新
验证:检查状态更改:***在这里写什么?***”
私有的
def检查更新时的def检查
如果是循环的?
将“层次结构是循环的”
错误。添加(:pid,“它是循环的”)
elsif(获取高度(id)+获取深度>=2)
将“超出高度限制”
错误。添加(:pid,“超出高度限制”)
elsif计数\u子项>=4
错误。添加(:pid,“超出子项限制”)
结束
放入“更新时一切正常”
结束
看一看。要仅在activestatus
从active
更改为inactive
时运行验证,只需在自定义验证方法中添加一行即可:
def check_on_update
return unless activestatus_changed?(from: 'active', to: 'inactive')
# your validation code
end
您可以使用ActiveModel::Dirty
if activestatus_was == 'active' && activestatus == 'inactive'
# validation logic goes here
end
更多信息:
希望有帮助 您使用的Rails版本是什么?