Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #785: validates_confirmatio_of-allow_nil.patch

File validates_confirmatio_of-allow_nil.patch, 2.5 kB (added by ggarside, 1 year ago)

Adds :allow_nil option to validates_confirmation_of and tests

  • activerecord/test/validations_test.rb

    old new  
    206206    t.title_confirmation = "Parallel Lives" 
    207207    assert t.valid? 
    208208  end 
     209   
     210  def test_no_title_confirmation_allow_nil_false 
     211    Topic.validates_confirmation_of(:title, :allow_nil => false) 
    209212 
     213    t = Topic.new(:author_name => "Plutarch") 
     214    assert t.valid? 
     215 
     216    t.title_confirmation = "Parallel Lives" 
     217    assert !t.valid? 
     218 
     219    t.title_confirmation = nil 
     220    t.title = "Parallel Lives" 
     221    assert !t.valid? 
     222 
     223    t.title_confirmation = "Parallel Lives" 
     224    assert t.valid? 
     225  end 
     226   
     227 
    210228  def test_title_confirmation 
    211229    Topic.validates_confirmation_of(:title) 
    212230 
  • activerecord/lib/active_record/validations.rb

    old new  
    401401      # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should 
    402402      # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }).  The 
    403403      # method, proc or string should return or evaluate to a true or false value. 
     404      # * <tt>allow_nil</tt> - Specifies if this validation should pass if _confirmation is nil. (default is true) 
    404405      def validates_confirmation_of(*attr_names) 
    405         configuration = { :message => ActiveRecord::Errors.default_error_messages[:confirmation], :on => :save
     406        configuration = { :message => ActiveRecord::Errors.default_error_messages[:confirmation], :on => :save, :allow_nil => true
    406407        configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash) 
    407408 
    408409        attr_accessor *(attr_names.map { |n| "#{n}_confirmation" }) 
    409410 
    410         validates_each(attr_names, configuration) do |record, attr_name, value| 
    411           record.errors.add(attr_name, configuration[:message]) unless record.send("#{attr_name}_confirmation").nil? or value == record.send("#{attr_name}_confirmation") 
     411        validates_each(attr_names, configuration.reject { |k,v| k == :allow_nil }) do |record, attr_name, value| 
     412          record.errors.add(attr_name, configuration[:message]) unless (configuration[:allow_nil] && record.send("#{attr_name}_confirmation").nil?) or value == record.send("#{attr_name}_confirmation") 
    412413        end 
    413414      end 
    414415