mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-23 06:16:50 +00:00
Support passing a custom ArraySerializer for has_many associations
Thanks @phoet Closes #316
This commit is contained in:
parent
ebe3afe716
commit
49ab359a34
@ -30,6 +30,6 @@ module ActiveModel
|
||||
serializer.new(item, @options).serializable_object
|
||||
end
|
||||
end
|
||||
alias serializable_object serializable_array
|
||||
alias_method :serializable_object, :serializable_array
|
||||
end
|
||||
end
|
||||
|
||||
@ -158,10 +158,12 @@ end
|
||||
|
||||
def serialize(association)
|
||||
associated_data = send(association.name)
|
||||
if associated_data.respond_to?(:to_ary)
|
||||
if associated_data.respond_to?(:to_ary) &&
|
||||
!(association.serializer_class &&
|
||||
association.serializer_class <= ArraySerializer)
|
||||
associated_data.map { |elem| association.build_serializer(elem).serializable_hash }
|
||||
else
|
||||
association.build_serializer(associated_data).serializable_hash
|
||||
association.build_serializer(associated_data).serializable_object
|
||||
end
|
||||
end
|
||||
|
||||
@ -179,6 +181,6 @@ end
|
||||
hash = attributes
|
||||
hash.merge! associations
|
||||
end
|
||||
alias serializable_object serializable_hash
|
||||
alias_method :serializable_object, :serializable_hash
|
||||
end
|
||||
end
|
||||
|
||||
@ -129,6 +129,21 @@ module ActiveModel
|
||||
comments: [{ content: 'fake' }, { content: 'fake' }]
|
||||
}, @post_serializer.as_json)
|
||||
end
|
||||
|
||||
def test_associations_using_a_given_array_serializer
|
||||
@association.embed = :ids
|
||||
@association.embed_in_root = true
|
||||
@association.serializer_class = Class.new(ActiveModel::ArraySerializer) do
|
||||
def serializable_object
|
||||
{ my_content: ['fake'] }
|
||||
end
|
||||
end
|
||||
|
||||
assert_equal({
|
||||
'post' => { title: 'Title 1', body: 'Body 1', 'comment_ids' => @post.comments.map { |c| c.object_id } },
|
||||
comments: { my_content: ['fake'] }
|
||||
}, @post_serializer.as_json)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
Loading…
Reference in New Issue
Block a user