aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--activemodel/lib/active_model/serializer.rb6
-rw-r--r--activemodel/test/cases/serializer_test.rb26
2 files changed, 31 insertions, 1 deletions
diff --git a/activemodel/lib/active_model/serializer.rb b/activemodel/lib/active_model/serializer.rb
index c5b433df51..6e89eec09c 100644
--- a/activemodel/lib/active_model/serializer.rb
+++ b/activemodel/lib/active_model/serializer.rb
@@ -41,6 +41,10 @@ module ActiveModel
def associate(klass, attrs)
options = attrs.extract_options!
self._associations += attrs.map do |attr|
+ unless method_defined?(attr)
+ class_eval "def #{attr}() object.#{attr} end", __FILE__, __LINE__
+ end
+
options[:serializer] ||= const_get("#{attr.to_s.camelize}Serializer")
klass.new(attr, options)
end
@@ -79,7 +83,7 @@ module ActiveModel
hash = attributes
_associations.each do |association|
- associated_object = object.send(association.name)
+ associated_object = send(association.name)
hash[association.name] = association.serialize(associated_object, scope)
end
diff --git a/activemodel/test/cases/serializer_test.rb b/activemodel/test/cases/serializer_test.rb
index 37a675bc20..08dd73e03b 100644
--- a/activemodel/test/cases/serializer_test.rb
+++ b/activemodel/test/cases/serializer_test.rb
@@ -174,4 +174,30 @@ class SerializerTest < ActiveModel::TestCase
}
}, json)
end
+
+ def test_overridden_associations
+ author_serializer = Class.new(ActiveModel::Serializer) do
+ attributes :first_name
+ end
+
+ blog_serializer = Class.new(ActiveModel::Serializer) do
+ const_set(:PersonSerializer, author_serializer)
+ has_one :person
+
+ def person
+ object.author
+ end
+ end
+
+ user = User.new
+ blog = Blog.new
+ blog.author = user
+
+ json = blog_serializer.new(blog, user).as_json
+ assert_equal({
+ :person => {
+ :first_name => "Jose"
+ }
+ }, json)
+ end
end