我想为给定的验证调用编写自定义验证器:
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
我想根据Worker#graph_object
验证GraphObject#state
。因此,当Worker
传入:准备好或:有效状态时,GrapObject
有效。我想尽可能多地重用ActiveModel。
验证文档描述了设置自定义验证器的过程,但我无法弄清楚如何操作。
我想我必须从这开始:
class GraphObjectTypeValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
end
end
value = record.graph_object
?)可能validates :graph_object, graph_object_type: {inclusion: [:ready, :active]}
未正确定义?
答案 0 :(得分:2)
好吧,我想我想出来了 - 我喜欢调试!谁需要撬!
这样做的一种方法是:
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
[:ready, :active]
数组Worker
GraphObject
:graph_object
符号