Skip to content

Commit 386a567

Browse files
committed
Evaluate association blocks as scopes on the association
1 parent 3e8290a commit 386a567

File tree

2 files changed

+11
-3
lines changed

2 files changed

+11
-3
lines changed

lib/active_model/serializer/reflection.rb

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,16 @@ class Serializer
77
# class PostSerializer < ActiveModel::Serializer
88
# has_one :author, serializer: AuthorSerializer
99
# has_many :comments
10+
# has_many :comments, key: :last_comments do
11+
# last(1)
12+
# end
1013
# end
1114
#
15+
# Notice that the association block is evaluated in the context of the association.
16+
# Specifically, the association 'comments' is evaluated two different ways:
17+
# 1) as 'comments' and named 'comments'.
18+
# 2) as 'comments.last(1)' and named 'last_comments'.
19+
#
1220
# PostSerializer._reflections #=>
1321
# # [
1422
# # HasOneReflection.new(:author, serializer: AuthorSerializer),
@@ -33,7 +41,7 @@ def value(instance)
3341

3442
def self.build_reader(name, block)
3543
if block
36-
->(instance) { instance.instance_eval(&block) }
44+
->(instance) { instance.read_attribute_for_serialization(name).instance_eval(&block) }
3745
else
3846
->(instance) { instance.read_attribute_for_serialization(name) }
3947
end

test/serializers/associations_test.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -128,8 +128,8 @@ def test_associations_custom_keys
128128

129129
class InlineAssociationTestPostSerializer < ActiveModel::Serializer
130130
has_many :comments
131-
has_many :last_comments do
132-
object.comments.last(1)
131+
has_many :comments, key: :last_comments do
132+
last(1)
133133
end
134134
end
135135

0 commit comments

Comments
 (0)