mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-25 07:16:49 +00:00
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:
@@ -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?
|
||||
|
||||
Reference in New Issue
Block a user