【问题标题】:How do I add a validation to a singleton_class only?如何仅向 singleton_class 添加验证?
【发布时间】:2013-08-17 00:51:58
【问题描述】:

当我向 singleton_class 添加验证时,它似乎被分配给了基类,并且两者都不会触发。

class Example
  attr_accessor :title, :some_boolean
  include ActiveModel::Validations
end


puts Example.validators  # []

with_validations = Example.new
with_validations.singleton_class.send :validates, :title, :presence => true

puts with_validations.valid?  #true

puts Example.validators.length # 1

我希望发生的事情:

with_validations.valid?  # false
Example.new.valid?       # true

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activemodel


    【解决方案1】:

    您可以使用 'on' 选项进行验证。

    validates :title, presence: true, on: :draft
    
    example = Example.new
    example.valid? # true
    example.valid?(:draft) #false
    

    【讨论】:

      猜你喜欢
      • 2021-03-11
      • 2011-03-30
      • 1970-01-01
      • 1970-01-01
      • 2023-01-19
      • 2017-11-04
      • 1970-01-01
      • 1970-01-01
      • 2018-12-23
      相关资源
      最近更新 更多