Make Associations in root work with ArraySerializer

Closes #414
This commit is contained in:
Santiago Pastorino 2013-10-31 16:51:57 -02:00
parent 5a92e00b51
commit 5598bb0f79
2 changed files with 59 additions and 0 deletions

View File

@ -37,5 +37,27 @@ module ActiveModel
end
end
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

View File

@ -193,5 +193,42 @@ module ActionController
assert_equal '{"my":[{"name":"Name 1","description":"Description 1"}]}', @response.body
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