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

Ticket #10518: updated_invalid_has_one_patch.patch

File updated_invalid_has_one_patch.patch, 2.0 kB (added by rubyruy, 2 years ago)
  • activerecord/lib/active_record/associations.rb

    old new  
    783783            end 
    784784          end 
    785785          after_save method_name 
    786  
     786          add_single_associated_save_callbacks(reflection.name) 
    787787          association_accessor_methods(reflection, HasOneAssociation) 
    788788          association_constructor_method(:build,  reflection, HasOneAssociation) 
    789789          association_constructor_method(:create, reflection, HasOneAssociation) 
     
    11411141          end 
    11421142        end 
    11431143         
     1144         def add_single_associated_save_callbacks(association_name) 
     1145           method_name = "validate_associated_records_for_#{association_name}".to_sym 
     1146           define_method(method_name) do 
     1147             association = instance_variable_get("@#{association_name}") 
     1148             if !association.nil? 
     1149               errors.add "#{association_name}" unless association.target.nil? || association.valid? 
     1150             end 
     1151           end 
     1152         
     1153           validate method_name 
     1154         end 
     1155         
    11441156        def add_multiple_associated_save_callbacks(association_name) 
    11451157          method_name = "validate_associated_records_for_#{association_name}".to_sym 
    11461158          ivar = "@#{association_name}" 
  • activerecord/test/cases/associations_test.rb

    old new  
    433433    assert_equal a, firm.account 
    434434    assert_equal a, firm.account(true) 
    435435  end 
     436   
     437  def test_save_fails_for_invalid_has_one 
     438    firm = Firm.find(:first) 
     439    assert firm.valid? 
     440     
     441    firm.account = Account.new 
     442     
     443    assert !firm.account.valid? 
     444    assert !firm.valid? 
     445    assert !firm.save 
     446    assert_equal "is invalid", firm.errors.on("account") 
     447  end 
    436448 
    437449  def test_assignment_before_either_saved 
    438450    firm = Firm.new("name" => "GlobalMegaCorp")