Evaluate association blocks as scopes on the association

This commit is contained in:
Benjamin Fleischer 2015-12-04 13:58:22 -06:00
parent 3e8290a923
commit 386a567dfc
2 changed files with 11 additions and 3 deletions

View File

@ -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

View File

@ -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