From c2e61aa61540802e5a5d9b54ff04b803d770eff6 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Sun, 10 Jun 2012 16:23:34 +0100 Subject: Ensure that mass assignment options are preserved There are two possible scenarios where the @mass_assignment_options instance variable can become corrupted: 1. If the assign_attributes doesn't complete correctly, then subsequent calls to a nested attribute assignment method will use whatever options were passed to the previous assign_attributes call. 2. With nested assign_attributes calls, the inner call will overwrite the current options. This will only affect nested attributes as the attribute hash is sanitized before any methods are called. To fix this we save the current options in a local variable and then restore these options in an ensure block. --- .../test/cases/mass_assignment_security_test.rb | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) (limited to 'activerecord/test/cases') diff --git a/activerecord/test/cases/mass_assignment_security_test.rb b/activerecord/test/cases/mass_assignment_security_test.rb index 2f98d3c646..1b5421c25e 100644 --- a/activerecord/test/cases/mass_assignment_security_test.rb +++ b/activerecord/test/cases/mass_assignment_security_test.rb @@ -878,4 +878,26 @@ class MassAssignmentSecurityNestedAttributesTest < ActiveRecord::TestCase assert_all_attributes(person.best_friends.first) end + def test_mass_assignment_options_are_reset_after_exception + person = NestedPerson.create!({ :first_name => 'David', :gender => 'm' }, :as => :admin) + person.create_best_friend!({ :first_name => 'Jeremy', :gender => 'm' }, :as => :admin) + + attributes = { :best_friend_attributes => { :comments => 'rides a sweet bike' } } + assert_raises(RuntimeError) { person.assign_attributes(attributes, :as => :admin) } + assert_equal 'm', person.best_friend.gender + + person.best_friend_attributes = { :gender => 'f' } + assert_equal 'm', person.best_friend.gender + end + + def test_mass_assignment_options_are_nested_correctly + person = NestedPerson.create!({ :first_name => 'David', :gender => 'm' }, :as => :admin) + person.create_best_friend!({ :first_name => 'Jeremy', :gender => 'm' }, :as => :admin) + + attributes = { :best_friend_first_name => 'Josh', :best_friend_attributes => { :gender => 'f' } } + person.assign_attributes(attributes, :as => :admin) + assert_equal 'Josh', person.best_friend.first_name + assert_equal 'f', person.best_friend.gender + end + end -- cgit v1.2.3