Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Specify type of singular assication during serialization #8352

Merged
merged 1 commit into from Nov 28, 2012
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions activemodel/CHANGELOG.md
@@ -1,5 +1,7 @@
## Rails 4.0.0 (unreleased) ##

* Specify type of singular association during serialization *Steve Klabnik*

* Fixed length validator to correctly handle nil values. Fixes #7180.

*Michal Zima*
Expand Down
7 changes: 6 additions & 1 deletion activemodel/lib/active_model/serializers/xml.rb
Expand Up @@ -149,7 +149,12 @@ def add_associations(association, records, opts)
end
else
merged_options[:root] = association.to_s
records.to_xml(merged_options)

unless records.class.to_s.underscore == association.to_s
merged_options[:type] = records.class.name
end

records.to_xml merged_options
end
end

Expand Down
12 changes: 10 additions & 2 deletions activemodel/test/cases/serializers/xml_serialization_test.rb
Expand Up @@ -6,12 +6,12 @@
class Contact
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

Expand Down Expand Up @@ -56,6 +56,9 @@ def setup
@contact.address.zip = 11111
@contact.address.apt_number = 35
@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
Expand Down Expand Up @@ -256,4 +259,9 @@ def to_ary
assert_match %r{<address>}, xml
assert_match %r{<apt-number type="integer">}, xml
end

test "association with sti" do
xml = @contact.to_xml(include: :contact)
assert xml.include?(%(<contact type="SerializableContact">))
end
end