【问题标题】:Custom ActiveModel Validator Ruby自定义 ActiveModel 验证器 Ruby
【发布时间】:2015-09-27 12:40:16
【问题描述】:

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

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。所以Worker 在传入的GrapObject 处于:ready:active 状态时有效。我想尽可能多地重用 ActiveModel。

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

我想我必须从这个开始:

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

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

【问题讨论】:

    标签: ruby validation activemodel


    【解决方案1】:

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

    一种方法是:

    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 符号

    【讨论】:

      猜你喜欢
      • 2014-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-08
      • 2011-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多