Rails 1.2.1 and Serialize

January 21st, 2007

I just updated to Rails 1.2.1 and tried it out on one of my applications. I’m getting some test failures because one of my models has an attribute that’s serialized as another class. In some cases, this attribute may be nil, which used to work fine, but now causes a SerializationTypeMismatch error, because when unserialize_attribute gets called it sees an object of type NilClass instead of the serialize target class.

I looked at the source and found unserialize_attribute in active_record/base and it’s unchanged from Rails 1.1.6, so best I can tell is in Rails 1.1.6 it was testing for nil before attempting to unserialize an attribute. I had a method that checks for this particular attribute being nil so I could change output depending on whether that attribute was there or not. So something definitely changed…

My workaround for now is to overwrite the unserialize_attribute method for that particular model. I copied the method out of activerecord/base and added one little thing:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Returns the unserialized object of the attribute.
def unserialize_attribute(attr_name)
  unserialized_object = object_from_yaml(@attributes[attr_name])

  if unserialized_object.is_a?(self.class.serialized_attributes[attr_name])
    @attributes[attr_name] = unserialized_object
  # added to allow for a nil object
  elsif unserialized_object.nil?
    nil
  else
    raise SerializationTypeMismatch,
      "#{attr_name} was supposed to be a #{self.class.serialized_attributes[attr_name]}, but was a #{unserialized_object.class.to_s}"
  end
end

This seems to work, so I get behavior I had previously in Rails 1.1.6. I was planning on refactoring this model anyway, because I didn’t like using serialize for these particular attributes – I had set it up that way several months ago and now things have changed, so this gives me a reason to go ahead and get my re-factoring underway.

1 Response to “Rails 1.2.1 and Serialize”

  1. steve odom Says:

    This saved me. Thanks.

Sorry, comments are closed for this article.