Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Don't instantiate attribute values in columns_hash
This bug only occurs on 4-2-stable. The conditions to make it occur
require doing a number of pretty dirty things. All of the following must
be true (roughly in order)

- The column is of a type which coerces to a complex data structure
- The data structure has mutability which is not protected by a shallow
  copy
- You are calling `.dup` on records which have never read or assigned
  that field
- You are mutating values deep inside the datastructure on records which
  have never had a value assigned

The reason this manifested through `.dup` on an Active Record model was
due to how we calculated changes in 4.2, which forced values to be
assigned on the defaults, and as per our documentation we only perform a
shallow copy of attributes, not a deep one. This issue does not occur on
5.0 and later due to sweeping changes in how duplication and dirty
tracking occur.

Fixes #25954
  • Loading branch information
sgrif committed Jul 27, 2016
1 parent 4889b7d commit 6fd5348
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/model_schema.rb
Expand Up @@ -247,7 +247,7 @@ def type_for_attribute(attr_name) # :nodoc:
# Returns a hash where the keys are column names and the values are
# default values when instantiating the AR object for this table.
def column_defaults
_default_attributes.to_hash
_default_attributes.dup.to_hash
end

def _default_attributes # :nodoc:
Expand Down
26 changes: 26 additions & 0 deletions activerecord/test/cases/dirty_test.rb
Expand Up @@ -767,6 +767,32 @@ def catchphrase
assert_equal({"catchphrase" => nil}, pirate_clone.changed_attributes)
end

test "duplicating a record does not cause default values to be shared across instances" do
serializer = Module.new do
def self.load(value)
["hello"]
end

def self.dump(value)
value
end
end

klass = Class.new(ActiveRecord::Base) do
self.table_name = "topics"

serialize :content, serializer
end

assert_equal ["hello"], klass.new.content

klass.new.dup

klass.new.content.first << "world"

assert_equal ["hello"], klass.new.content
end

private
def with_partial_writes(klass, on = true)
old = klass.partial_writes?
Expand Down

0 comments on commit 6fd5348

Please sign in to comment.