Skip to content

Error calling dup() on ActiveRecord model with serialized field #5797

@gmcnaughton

Description

@gmcnaughton

Starting with Rails >=3.2.2, I get the following error when calling dup() on a model with a serialized field:

# app/models/my_obj.rb
class MyObj < ActiveRecord::Base
  serialize :content, JSON
end
$ rails c
1.9.3-p0 :001 > MyObj.new(:content => {"a" => "b"}).dup
TypeError: can't convert Hash into String
  from gems/json-1.6.6/lib/json/common.rb:148:in `initialize'
  from gems/json-1.6.6/lib/json/common.rb:148:in `new'
  from gems/json-1.6.6/lib/json/common.rb:148:in `parse'
  from gems/json-1.6.6/lib/json/common.rb:320:in `load'
  from gems/activerecord-3.2.3/lib/active_record/attribute_methods/serialization.rb:24:in `unserialize'
  from gems/activerecord-3.2.3/lib/active_record/attribute_methods/serialization.rb:15:in `unserialized_value'
  from gems/activerecord-3.2.3/lib/active_record/attribute_methods/read.rb:82:in `__temp__'
  from gems/activerecord-3.2.3/lib/active_record/attribute_methods/read.rb:46:in `type_cast_attribute'
  from gems/activerecord-3.2.3/lib/active_record/attribute_methods/read.rb:126:in `read_attribute'
  from gems/activerecord-3.2.3/lib/active_record/attribute_methods.rb:200:in `attribute_for_inspect'
  from gems/activerecord-3.2.3/lib/active_record/base.rb:643:in `block in inspect'
  from gems/activerecord-3.2.3/lib/active_record/base.rb:641:in `collect'
  from gems/activerecord-3.2.3/lib/active_record/base.rb:641:in `inspect'
  from gems/railties-3.2.3/lib/rails/commands/console.rb:47:in `start'
  from gems/railties-3.2.3/lib/rails/commands/console.rb:8:in `start'
  from gems/railties-3.2.3/lib/rails/commands.rb:41:in `<top (required)>'
  from script/rails:6:in `require'
  from script/rails:6:in `<main>'1.9.3-p0 :002

The above code works on Rails 3.2.1. It appears to be related to this commit for issue #4837.

The problem appears to be that after duping, the code tries to unserialize an already-unserialized value. The JSON parser chokes when it receives a Hash instead of a string.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions