mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-22 22:06:50 +00:00
HasOne nil object should return [] under embedded key.
Ensure that @wrap_in_array is always respected when set to true even when associated object is nil.
This commit is contained in:
parent
b6520315d8
commit
8ca4d4fcd6
@ -9,12 +9,15 @@ module ActiveModel
|
||||
|
||||
attr_reader :object
|
||||
|
||||
def initialize(object, options=nil)
|
||||
def initialize(object, options={})
|
||||
@object = object
|
||||
@wrap_in_array = options[:_wrap_in_array]
|
||||
end
|
||||
|
||||
def as_json(options={})
|
||||
@object.as_json
|
||||
return [] if @object.nil? && @wrap_in_array
|
||||
hash = @object.as_json
|
||||
@wrap_in_array ? [hash] : hash
|
||||
end
|
||||
alias serializable_hash as_json
|
||||
alias serializable_object as_json
|
||||
|
||||
@ -183,7 +183,7 @@ end
|
||||
end
|
||||
|
||||
def serializable_object(options={})
|
||||
return nil if object.nil?
|
||||
return @wrap_in_array ? [] : nil if @object.nil?
|
||||
hash = attributes
|
||||
hash.merge! associations
|
||||
@wrap_in_array ? [hash] : hash
|
||||
|
||||
@ -106,6 +106,21 @@ module ActiveModel
|
||||
}, @user_serializer.serializable_hash)
|
||||
end
|
||||
|
||||
def test_associations_embedding_nil_ids_including_objects_serialization_using_as_json
|
||||
@association.embed = :ids
|
||||
@association.embed_in_root = true
|
||||
@user.instance_eval do
|
||||
def profile
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
assert_equal({
|
||||
'user' => { name: 'Name 1', email: 'mail@server.com', 'profile_id' => nil },
|
||||
'profiles' => []
|
||||
}, @user_serializer.as_json)
|
||||
end
|
||||
|
||||
def test_associations_embedding_ids_including_objects_serialization_using_as_json
|
||||
@association.embed = :ids
|
||||
@association.embed_in_root = true
|
||||
|
||||
Loading…
Reference in New Issue
Block a user