ruby-on-rails - 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
解决方案
看看ActiveModel::Dirty
。activestatus
仅在更改active
为inactive
仅向自定义验证方法添加一行时才运行验证:
def check_on_update
return unless activestatus_changed?(from: 'active', to: 'inactive')
# your validation code
end
推荐阅读
- javascript - 如何将 2 个数据模型源传递给 SearchField
- cors - 无法加载外部 API 定义
- php - 非常简单的 excel 文件到 php 数组返回给我太多的嵌套数组?
- c - 是否有任何用于连接 AWS IoT 的 Samsung Artik 库/头文件?
- python - 为什么 loss 和 acc 在训练中会出现峰值波动?
- sql - 如何按值进行sql选择查询?
- r - 将 VisNetwork (R) 图导出到 Gephi
- r - 有没有办法根据数据框的列范围更改行的值?
- amazon-web-services - 使用 AWS SDK for Java 2.x 检查 S3 对象的元数据
- angular - angular 6 指令仅接受十进制前的 1 个数字,例如 2.12548