mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-22 22:06: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
|
||||
# object without the root.
|
||||
def serializable_hash
|
||||
return nil if @object.nil?
|
||||
instrument(:serialize, :serializer => self.class.name) do
|
||||
@node = attributes
|
||||
instrument :associations do
|
||||
|
||||
@ -254,6 +254,28 @@ class SerializerTest < ActiveModel::TestCase
|
||||
assert_equal({ :my_blog => { :author => nil } }, serializer.new(blog, :scope => user).as_json)
|
||||
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
|
||||
user = User.new
|
||||
blog = Blog.new
|
||||
|
||||
Loading…
Reference in New Issue
Block a user