mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-24 14:56:50 +00:00
Don't fail if object is nil, render null
This commit is contained in:
parent
58a063eff0
commit
c7a420d295
@ -267,6 +267,7 @@ module ActiveModel
|
|||||||
# Returns a hash representation of the serializable
|
# Returns a hash representation of the serializable
|
||||||
# object without the root.
|
# object without the root.
|
||||||
def serializable_hash
|
def serializable_hash
|
||||||
|
return nil if @object.nil?
|
||||||
instrument(:serialize, :serializer => self.class.name) do
|
instrument(:serialize, :serializer => self.class.name) do
|
||||||
@node = attributes
|
@node = attributes
|
||||||
instrument :associations do
|
instrument :associations do
|
||||||
|
|||||||
@ -254,6 +254,28 @@ class SerializerTest < ActiveModel::TestCase
|
|||||||
assert_equal({ :my_blog => { :author => nil } }, serializer.new(blog, :scope => user).as_json)
|
assert_equal({ :my_blog => { :author => nil } }, serializer.new(blog, :scope => user).as_json)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def test_nil_root_object
|
||||||
|
user = User.new
|
||||||
|
blog = nil
|
||||||
|
|
||||||
|
serializer = Class.new(BlogSerializer) do
|
||||||
|
root false
|
||||||
|
end
|
||||||
|
|
||||||
|
assert_equal(nil, serializer.new(blog, :scope => user).as_json)
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_custom_root_with_nil_root_object
|
||||||
|
user = User.new
|
||||||
|
blog = nil
|
||||||
|
|
||||||
|
serializer = Class.new(BlogSerializer) do
|
||||||
|
root :my_blog
|
||||||
|
end
|
||||||
|
|
||||||
|
assert_equal({ :my_blog => nil }, serializer.new(blog, :scope => user).as_json)
|
||||||
|
end
|
||||||
|
|
||||||
def test_false_root
|
def test_false_root
|
||||||
user = User.new
|
user = User.new
|
||||||
blog = Blog.new
|
blog = Blog.new
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user