Skip to content

Commit

Permalink
Merge pull request #5810 from kennyj/fix_5797
Browse files Browse the repository at this point in the history
Fix #5797. Error calling dup method on AR model with serialized field
  • Loading branch information
tenderlove committed May 30, 2012
2 parents 7c1b61e + d09b2fd commit 1b07522
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -72,12 +72,13 @@ def serialize(attr_name, class_name = Object)
self.serialized_attributes = serialized_attributes.merge(attr_name.to_s => coder)
end

def initialize_attributes(attributes) #:nodoc:
super
def initialize_attributes(attributes, options = {}) #:nodoc:
serialized = (options.delete(:serialized) { true }) ? :serialized : :unserialized
super(attributes, options)

serialized_attributes.each do |key, coder|
if attributes.key?(key)
attributes[key] = Attribute.new(coder, attributes[key], :serialized)
attributes[key] = Attribute.new(coder, attributes[key], serialized)
end
end

Expand Down
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/core.rb
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ def init_with(coder)
##
def initialize_dup(other) # :nodoc:
cloned_attributes = other.clone_attributes(:read_attribute_before_type_cast)
self.class.initialize_attributes(cloned_attributes)
self.class.initialize_attributes(cloned_attributes, :serialized => false)

cloned_attributes.delete(self.class.primary_key)

Expand Down
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/locking/optimistic.rb
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ def update_counters(id, counters)
# start the lock version at zero. Note we can't use
# <tt>locking_enabled?</tt> at this point as
# <tt>@attributes</tt> may not have been initialized yet.
def initialize_attributes(attributes) #:nodoc:
def initialize_attributes(attributes, options = {}) #:nodoc:
if attributes.key?(locking_column) && lock_optimistically
attributes[locking_column] ||= 0
end
Expand Down
9 changes: 9 additions & 0 deletions activerecord/test/cases/base_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1309,6 +1309,15 @@ def test_serialized_attribute_before_type_cast_returns_unserialized_value
assert_equal({ :foo => :bar }, t.content_before_type_cast)
end

def test_serialized_attribute_calling_dup_method
klass = Class.new(ActiveRecord::Base)
klass.table_name = "topics"
klass.serialize :content, JSON

t = klass.new(:content => { :foo => :bar }).dup
assert_equal({ :foo => :bar }, t.content_before_type_cast)
end

def test_serialized_attribute_declared_in_subclass
hash = { 'important1' => 'value1', 'important2' => 'value2' }
important_topic = ImportantTopic.create("important" => hash)
Expand Down

0 comments on commit 1b07522

Please sign in to comment.