Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

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.
  • Loading branch information...
commit 8ca4d4fcd60aee96c4000ce98a50c37c07bc8a40 1 parent b652031
@kenips kenips authored xymbol committed
View
7 lib/active_model/default_serializer.rb
@@ -9,12 +9,15 @@ class DefaultSerializer
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
View
2  lib/active_model/serializer.rb
@@ -183,7 +183,7 @@ def serialize_ids(association)
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
View
15 test/unit/active_model/serializer/has_one_test.rb
@@ -106,6 +106,21 @@ def test_associations_embedding_ids_including_objects_serialization_using_serial
}, @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
Please sign in to comment.
Something went wrong with that request. Please try again.