mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-24 14:56:50 +00:00
Evaluate association blocks as scopes on the association
This commit is contained in:
parent
3e8290a923
commit
386a567dfc
@ -7,8 +7,16 @@ module ActiveModel
|
|||||||
# class PostSerializer < ActiveModel::Serializer
|
# class PostSerializer < ActiveModel::Serializer
|
||||||
# has_one :author, serializer: AuthorSerializer
|
# has_one :author, serializer: AuthorSerializer
|
||||||
# has_many :comments
|
# has_many :comments
|
||||||
|
# has_many :comments, key: :last_comments do
|
||||||
|
# last(1)
|
||||||
|
# end
|
||||||
# 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 #=>
|
# PostSerializer._reflections #=>
|
||||||
# # [
|
# # [
|
||||||
# # HasOneReflection.new(:author, serializer: AuthorSerializer),
|
# # HasOneReflection.new(:author, serializer: AuthorSerializer),
|
||||||
@ -33,7 +41,7 @@ module ActiveModel
|
|||||||
|
|
||||||
def self.build_reader(name, block)
|
def self.build_reader(name, block)
|
||||||
if block
|
if block
|
||||||
->(instance) { instance.instance_eval(&block) }
|
->(instance) { instance.read_attribute_for_serialization(name).instance_eval(&block) }
|
||||||
else
|
else
|
||||||
->(instance) { instance.read_attribute_for_serialization(name) }
|
->(instance) { instance.read_attribute_for_serialization(name) }
|
||||||
end
|
end
|
||||||
|
|||||||
@ -128,8 +128,8 @@ module ActiveModel
|
|||||||
|
|
||||||
class InlineAssociationTestPostSerializer < ActiveModel::Serializer
|
class InlineAssociationTestPostSerializer < ActiveModel::Serializer
|
||||||
has_many :comments
|
has_many :comments
|
||||||
has_many :last_comments do
|
has_many :comments, key: :last_comments do
|
||||||
object.comments.last(1)
|
last(1)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user