Raise error when associations cannot be included

include! only works when the source serializer has a root set. The
as_json method sets up some state for the include! method. If a child
association has associations with `:include => true` or `root foo,
:include => true` would cause an undefined method error for `NilClass`.
This is entirely unhelpful for the end user.

This commit raise an error when this situation occurs. It makes it clear
that it's not a problem with AMS but the serialization graph.
This commit is contained in:
twinturbo
2012-07-16 13:41:15 +02:00
parent f2714ace8a
commit 486d282922
2 changed files with 90 additions and 1 deletions

View File

@@ -108,6 +108,18 @@ module ActiveModel
# end
#
class Serializer
class IncludeError < StandardError
attr_reader :source, :association
def initialize(source, association)
@source, @association = source, association
end
def to_s
"Cannot serialize #{association} when #{source} does not have a root!"
end
end
module Associations #:nodoc:
class Config #:nodoc:
class_attribute :options
@@ -502,7 +514,9 @@ module ActiveModel
if association.embed_ids?
node[association.key] = association.serialize_ids
if association.embed_in_root?
if association.embed_in_root? && hash.nil?
raise IncludeError.new(self.class, association.name)
elsif association.embed_in_root?
merge_association hash, association.root, association.serialize_many, unique_values
end
elsif association.embed_objects?