aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/base.rb
diff options
context:
space:
mode:
authorGuillermo Álvarez <guillermo@cientifico.net>2011-02-03 00:26:39 +0100
committerAaron Patterson <aaron.patterson@gmail.com>2011-02-03 09:08:45 -0800
commit351331fb343cdf17baa078943898ded6caff9d65 (patch)
tree8b57684788395cbe899a27c24f51a990eb416584 /activerecord/lib/active_record/base.rb
parent080345baca1076a9788dff4803153600aec31f86 (diff)
downloadrails-351331fb343cdf17baa078943898ded6caff9d65.tar.gz
rails-351331fb343cdf17baa078943898ded6caff9d65.tar.bz2
rails-351331fb343cdf17baa078943898ded6caff9d65.zip
Make serialized columns with explicit object_type return a new instance of the object instead of nil
Diffstat (limited to 'activerecord/lib/active_record/base.rb')
-rw-r--r--activerecord/lib/active_record/base.rb24
1 files changed, 20 insertions, 4 deletions
diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb
index 0941700803..e0957e2849 100644
--- a/activerecord/lib/active_record/base.rb
+++ b/activerecord/lib/active_record/base.rb
@@ -249,6 +249,17 @@ module ActiveRecord #:nodoc:
# user = User.create(:preferences => %w( one two three ))
# User.find(user.id).preferences # raises SerializationTypeMismatch
#
+ # When you specify a class option, the default value for that attribute will be a new
+ # instance of that class.
+ #
+ # class User < ActiveRecord::Base
+ # serialize :preferences, OpenStruct
+ # end
+ #
+ # user = User.new
+ # user.preferences.theme_color = "red"
+ #
+ #
# == Single table inheritance
#
# Active Record allows inheritance by storing the name of the class in a column that by
@@ -1409,6 +1420,7 @@ MSG
@changed_attributes = {}
ensure_proper_type
+ set_serialized_attributes
populate_with_current_scope_attributes
self.attributes = attributes unless attributes.nil?
@@ -1447,10 +1459,7 @@ MSG
def init_with(coder)
@attributes = coder['attributes']
- (@attributes.keys & self.class.serialized_attributes.keys).each do |key|
- coder = self.class.serialized_attributes[key]
- @attributes[key] = coder.load @attributes[key]
- end
+ set_serialized_attributes
@attributes_cache, @previously_changed, @changed_attributes = {}, {}, {}
@association_cache = {}
@@ -1461,6 +1470,13 @@ MSG
run_callbacks :initialize
end
+ def set_serialized_attributes
+ (@attributes.keys & self.class.serialized_attributes.keys).each do |key|
+ coder = self.class.serialized_attributes[key]
+ @attributes[key] = coder.load @attributes[key]
+ end
+ end
+
# Specifies how the record is dumped by +Marshal+.
#
# +_dump+ emits a marshalled hash which has been passed to +encode_with+. Override this