From 2c240cf2e063251069ded14cc923125c858b0370 Mon Sep 17 00:00:00 2001 From: Adman65 Date: Fri, 9 Dec 2011 16:16:09 +0100 Subject: [PATCH] Implicit detection for has_many serializer --- lib/active_model/serializer.rb | 2 ++ test/serializer_test.rb | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index ef68072c..14220ed0 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -138,6 +138,8 @@ module ActiveModel # to determine the serializer if options[:key] && !options[:serializer] options[:serializer] = const_get("#{options[:key].to_s.camelize.singularize}Serializer") + elsif !options[:serializer] && klass == Associations::HasMany + options[:serializer] = const_get("#{attr.to_s.camelize.singularize}Serializer") else options[:serializer] ||= const_get("#{attr.to_s.camelize}Serializer") end diff --git a/test/serializer_test.rb b/test/serializer_test.rb index 3a65e1ab..b4e50161 100644 --- a/test/serializer_test.rb +++ b/test/serializer_test.rb @@ -211,6 +211,30 @@ class SerializerTest < ActiveModel::TestCase }, json) end + def test_implicit_serializer_for_has_many + blog_with_posts = Class.new(Blog) do + attr_accessor :posts + end + + blog_serializer = Class.new(ActiveModel::Serializer) do + const_set(:PostSerializer, PostSerializer) + has_many :posts + end + + user = User.new + blog = blog_with_posts.new + blog.posts = [Post.new(:title => 'test')] + + json = blog_serializer.new(blog, user).as_json + assert_equal({ + :posts => [{ + :title => "test", + :body => nil, + :comments => [] + }] + }, json) + end + def test_overridden_associations author_serializer = Class.new(ActiveModel::Serializer) do attributes :first_name