如何仅向singleton_class添加验证?

时间:2013-08-17 00:51:59

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

当我向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

1 个答案:

答案 0 :(得分:0)

您可以使用“开启”选项进行验证。

validates :title, presence: true, on: :draft

example = Example.new
example.valid? # true
example.valid?(:draft) #false