From 03372ea61da0570d694a8a11b43206d602808fa3 Mon Sep 17 00:00:00 2001 From: Mateo Murphy Date: Fri, 20 Mar 2015 00:22:46 -0400 Subject: [PATCH] Fix options merge order in `each_association` Custom association serializers were getting clobbered when using an each serializer. --- lib/active_model/serializer.rb | 2 +- .../explicit_serializer_test.rb | 32 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index 7badb04a..9bddb6c5 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -187,7 +187,7 @@ module ActiveModel serializer = serializer_class.new( association_value, - serializer_from_options(association_options).merge(options) + options.merge(serializer_from_options(association_options)) ) if serializer_class if block_given? diff --git a/test/action_controller/explicit_serializer_test.rb b/test/action_controller/explicit_serializer_test.rb index cb8b2bd7..ee3f9db4 100644 --- a/test/action_controller/explicit_serializer_test.rb +++ b/test/action_controller/explicit_serializer_test.rb @@ -37,6 +37,24 @@ module ActionController render json: array, each_serializer: ProfilePreviewSerializer end + + def render_array_using_explicit_serializer_and_custom_serializers + @post = Post.new(title: 'New Post', body: 'Body') + @author = Author.new(name: 'Jane Blogger') + @author.posts = [@post] + @post.author = @author + @first_comment = Comment.new(id: 1, body: 'ZOMG A COMMENT') + @second_comment = Comment.new(id: 2, body: 'ZOMG ANOTHER COMMENT') + @post.comments = [@first_comment, @second_comment] + @first_comment.post = @post + @first_comment.author = nil + @second_comment.post = @post + @second_comment.author = nil + @blog = Blog.new(id: 23, name: 'AMS Blog') + @post.blog = @blog + + render json: [@post], each_serializer: PostPreviewSerializer + end end tests MyController @@ -73,6 +91,20 @@ module ActionController assert_equal expected.to_json, @response.body end + def test_render_array_using_explicit_serializer_and_custom_serializers + get :render_array_using_explicit_serializer_and_custom_serializers + + expected = [ + { "title" => "New Post", + "body" => "Body", + "id" => assigns(:post).id, + "comments" => [{"id" => 1}, {"id" => 2}], + "author" => { "id" => assigns(:author).id } + } + ] + + assert_equal expected.to_json, @response.body + end end end end