mirror of https://github.com/rails/rails
Fix nil has_one association
This commit is contained in:
parent
322f47898e
commit
7a28498b55
|
@ -31,11 +31,11 @@ module ActiveModel
|
|||
|
||||
class HasOne < Config
|
||||
def serialize(object, scope)
|
||||
serializer.new(object, scope).serializable_hash
|
||||
object && serializer.new(object, scope).serializable_hash
|
||||
end
|
||||
|
||||
def serialize_ids(object, scope)
|
||||
object.read_attribute_for_serialization(:id)
|
||||
object && object.read_attribute_for_serialization(:id)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
|
@ -259,4 +259,22 @@ class SerializerTest < ActiveModel::TestCase
|
|||
]
|
||||
}, serializer.as_json)
|
||||
end
|
||||
|
||||
def test_associations_with_nil_association
|
||||
user = User.new
|
||||
blog = Blog.new
|
||||
|
||||
json = BlogSerializer.new(blog, user).as_json
|
||||
assert_equal({
|
||||
:author => nil
|
||||
}, json)
|
||||
|
||||
serializer = Class.new(BlogSerializer) do
|
||||
def serializable_hash
|
||||
attributes.merge(association_ids)
|
||||
end
|
||||
end
|
||||
|
||||
assert_equal({ :author => nil }, serializer.new(blog, user).as_json)
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Reference in New Issue