Skip to content

Commit 03372ea

Browse files
committed
Fix options merge order in each_association
Custom association serializers were getting clobbered when using an each serializer.
1 parent 9058d5f commit 03372ea

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

lib/active_model/serializer.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,7 @@ def each_association(&block)
187187

188188
serializer = serializer_class.new(
189189
association_value,
190-
serializer_from_options(association_options).merge(options)
190+
options.merge(serializer_from_options(association_options))
191191
) if serializer_class
192192

193193
if block_given?

test/action_controller/explicit_serializer_test.rb

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,24 @@ def render_array_using_implicit_serializer
3737
render json: array,
3838
each_serializer: ProfilePreviewSerializer
3939
end
40+
41+
def render_array_using_explicit_serializer_and_custom_serializers
42+
@post = Post.new(title: 'New Post', body: 'Body')
43+
@author = Author.new(name: 'Jane Blogger')
44+
@author.posts = [@post]
45+
@post.author = @author
46+
@first_comment = Comment.new(id: 1, body: 'ZOMG A COMMENT')
47+
@second_comment = Comment.new(id: 2, body: 'ZOMG ANOTHER COMMENT')
48+
@post.comments = [@first_comment, @second_comment]
49+
@first_comment.post = @post
50+
@first_comment.author = nil
51+
@second_comment.post = @post
52+
@second_comment.author = nil
53+
@blog = Blog.new(id: 23, name: 'AMS Blog')
54+
@post.blog = @blog
55+
56+
render json: [@post], each_serializer: PostPreviewSerializer
57+
end
4058
end
4159

4260
tests MyController
@@ -73,6 +91,20 @@ def test_render_array_using_explicit_serializer
7391
assert_equal expected.to_json, @response.body
7492
end
7593

94+
def test_render_array_using_explicit_serializer_and_custom_serializers
95+
get :render_array_using_explicit_serializer_and_custom_serializers
96+
97+
expected = [
98+
{ "title" => "New Post",
99+
"body" => "Body",
100+
"id" => assigns(:post).id,
101+
"comments" => [{"id" => 1}, {"id" => 2}],
102+
"author" => { "id" => assigns(:author).id }
103+
}
104+
]
105+
106+
assert_equal expected.to_json, @response.body
107+
end
76108
end
77109
end
78110
end

0 commit comments

Comments
 (0)