Permalink
Browse files

When serialising a class, specify the type of any singular associatio…

…ns, if

necessary. Rails already correctly specifies the :type of any enumerable
association (e.g. a has_many association), but made no attempt to do so for
non-enumerables (e.g. a has_one association).
We must specify the :type of any polymorphic association. A has_one
association to a class which uses single-table inheritance is an example of
a polymorphic association.
Fixes #7471
  • Loading branch information...
1 parent 9896729 commit e7f7e35de1c3ac197d127e8187a74eaf774cbe56 @cliochris committed Oct 5, 2012
@@ -140,7 +140,9 @@ def add_associations(association, records, opts)
end
else
merged_options[:root] = association.to_s
- records.to_xml(merged_options)
+ association_name = association.to_s.tableize.singularize
+ record_type = { :type => ((records.class.to_s.underscore == association_name) ? nil : records.class.name) }
+ records.to_xml merged_options.merge(record_type)
end
end
@@ -7,12 +7,12 @@ class Contact
extend ActiveModel::Naming
include ActiveModel::Serializers::Xml
- attr_accessor :address, :friends
+ attr_accessor :address, :friends, :contact
remove_method :attributes if method_defined?(:attributes)
def attributes
- instance_values.except("address", "friends")
+ instance_values.except("address", "friends", "contact")
end
end
@@ -57,6 +57,9 @@ def setup
@contact.address.state = "CA"
@contact.address.zip = 11111
@contact.friends = [Contact.new, Contact.new]
+ @related_contact = SerializableContact.new
+ @related_contact.name = "related"
+ @contact.contact = @related_contact
end
test "should serialize default root" do
@@ -205,4 +208,9 @@ def setup
assert_match %r{<friends>}, xml
assert_match %r{<friend>}, xml
end
+
+ test "association with sti" do
+ xml = @contact.to_xml(:include => :contact)
+ assert xml.include?(%(<contact type="SerializableContact">))
+ end
end

0 comments on commit e7f7e35

Please sign in to comment.