mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-24 14:56:50 +00:00
parent
5a92e00b51
commit
5598bb0f79
@ -37,5 +37,27 @@ module ActiveModel
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
alias_method :serializable_object, :serializable_array
|
alias_method :serializable_object, :serializable_array
|
||||||
|
|
||||||
|
def serializable_data
|
||||||
|
embedded_in_root_associations.merge!(super)
|
||||||
|
end
|
||||||
|
|
||||||
|
def embedded_in_root_associations
|
||||||
|
hash = {}
|
||||||
|
@object.map do |item|
|
||||||
|
serializer_class = @each_serializer || Serializer.serializer_for(item) || DefaultSerializer
|
||||||
|
associations = serializer_class._associations
|
||||||
|
serializer = serializer_class.new(item, @options)
|
||||||
|
included_associations = serializer.filter(associations.keys)
|
||||||
|
associations.each do |(name, association)|
|
||||||
|
if included_associations.include? name
|
||||||
|
if association.embed_in_root?
|
||||||
|
hash[association.embedded_key] = serializer.serialize association
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
hash
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@ -193,5 +193,42 @@ module ActionController
|
|||||||
assert_equal '{"my":[{"name":"Name 1","description":"Description 1"}]}', @response.body
|
assert_equal '{"my":[{"name":"Name 1","description":"Description 1"}]}', @response.body
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
class ArrayEmbedingSerializerTest < ActionController::TestCase
|
||||||
|
def setup
|
||||||
|
super
|
||||||
|
@association = UserSerializer._associations[:profile]
|
||||||
|
@old_association = @association.dup
|
||||||
|
end
|
||||||
|
|
||||||
|
def teardown
|
||||||
|
super
|
||||||
|
UserSerializer._associations[:profile] = @old_association
|
||||||
|
end
|
||||||
|
|
||||||
|
class MyController < ActionController::Base
|
||||||
|
def initialize(*)
|
||||||
|
super
|
||||||
|
@user = User.new({ name: 'Name 1', email: 'mail@server.com', gender: 'M' })
|
||||||
|
end
|
||||||
|
attr_reader :user
|
||||||
|
|
||||||
|
def render_array_embeding_in_root
|
||||||
|
render json: [@user]
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
tests MyController
|
||||||
|
|
||||||
|
def test_render_array_embeding_in_root
|
||||||
|
@association.embed = :ids
|
||||||
|
@association.embed_in_root = true
|
||||||
|
|
||||||
|
get :render_array_embeding_in_root
|
||||||
|
assert_equal 'application/json', @response.content_type
|
||||||
|
|
||||||
|
assert_equal("{\"my\":[{\"name\":\"Name 1\",\"email\":\"mail@server.com\",\"profile_id\":#{@controller.user.profile.object_id}}],\"profiles\":[{\"name\":\"N1\",\"description\":\"D1\"}]}", @response.body)
|
||||||
|
end
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user