gpt4 book ai didi

ruby - 自定义 ActiveModel 验证器 Ruby

转载 作者:数据小太阳 更新时间:2023-10-29 09:02:12 26 4
gpt4 key购买 nike

我想为给定的验证调用编写自定义验证器:

class Worker
include ActiveModel::Validations

def initialize(graph_object)
@graph_object = graph_object
end

attr_accessor :graph_object

validates :graph_object, graph_object_type: {inclusion: [:ready, :active]}
end

class GraphObject
attr_accessor :state
end

我想根据 GraphObject#state 验证 Worker#graph_object。因此,当传入的GrapObject 处于:ready:active 状态时,Worker 有效。我想尽可能多地重用 ActiveModel。

验证文档描述了设置自定义验证器的过程,但我不知道该怎么做。

我想我必须从这个开始:

class GraphObjectTypeValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
end
end
  • 选项[:inclusion] = [:ready, :active]
  • record 是 Worker 的实例(我认为...)
  • value 我不知道(是 value = record.graph_object 吗?)
  • attribute 与 value 相同 - 不知道

也许 validates :graph_object, graph_object_type: {inclusion: [:ready, :active]} 没有正确定义?

最佳答案

好的,我想我明白了——我喜欢调试!谁需要 pry !

一种方法是:

class GraphObjectTypeValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
if options.key?(:inclusion) && not_included?(value.type)
record.errors.add(attribute, "wrong graph object type")
end
end

private

def not_included?(type)
!options[:inclusion].include?(type)
end
end
  • options[:inclusion]: [:ready, :active] 数组
  • 记录 Worker
  • 的实例
  • 值: GraphObject
  • 的实例
  • 属性: :graph_object 符号

关于ruby - 自定义 ActiveModel 验证器 Ruby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32808003/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com