2013-08-17 25 views
3

當我將驗證添加到singleton_class時,它似乎被分配給基類,而不會觸發它。如何僅向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 

回答

0

您可以通過 '上' 選項用做驗證。

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

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