mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-22 22:06:50 +00:00
Evaluate association blocks as scopes on the association
This commit is contained in:
parent
3e8290a923
commit
386a567dfc
@ -7,7 +7,15 @@ module ActiveModel
|
||||
# class PostSerializer < ActiveModel::Serializer
|
||||
# has_one :author, serializer: AuthorSerializer
|
||||
# has_many :comments
|
||||
# has_many :comments, key: :last_comments do
|
||||
# last(1)
|
||||
# end
|
||||
# end
|
||||
#
|
||||
# Notice that the association block is evaluated in the context of the association.
|
||||
# Specifically, the association 'comments' is evaluated two different ways:
|
||||
# 1) as 'comments' and named 'comments'.
|
||||
# 2) as 'comments.last(1)' and named 'last_comments'.
|
||||
#
|
||||
# PostSerializer._reflections #=>
|
||||
# # [
|
||||
@ -33,7 +41,7 @@ module ActiveModel
|
||||
|
||||
def self.build_reader(name, block)
|
||||
if block
|
||||
->(instance) { instance.instance_eval(&block) }
|
||||
->(instance) { instance.read_attribute_for_serialization(name).instance_eval(&block) }
|
||||
else
|
||||
->(instance) { instance.read_attribute_for_serialization(name) }
|
||||
end
|
||||
|
||||
@ -128,8 +128,8 @@ module ActiveModel
|
||||
|
||||
class InlineAssociationTestPostSerializer < ActiveModel::Serializer
|
||||
has_many :comments
|
||||
has_many :last_comments do
|
||||
object.comments.last(1)
|
||||
has_many :comments, key: :last_comments do
|
||||
last(1)
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user