提交 9504b44c 编写于 作者: S Steve Klabnik

Specify type of singular association during serialization

When serialising a class, specify the type of any singular associations, 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 STI association. A has_one
association to a class which uses single-table inheritance is an example of
this type of association.

Fixes #7471
上级 3e965e21
## Rails 4.0.0 (unreleased) ## ## Rails 4.0.0 (unreleased) ##
* Specify type of singular association during serialization *Steve Klabnik*
* Fixed length validator to correctly handle nil values. Fixes #7180. * Fixed length validator to correctly handle nil values. Fixes #7180.
*Michal Zima* *Michal Zima*
......
...@@ -149,7 +149,12 @@ def add_associations(association, records, opts) ...@@ -149,7 +149,12 @@ def add_associations(association, records, opts)
end end
else else
merged_options[:root] = association.to_s 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
end end
......
...@@ -6,12 +6,12 @@ ...@@ -6,12 +6,12 @@
class Contact class Contact
include ActiveModel::Serializers::Xml include ActiveModel::Serializers::Xml
attr_accessor :address, :friends attr_accessor :address, :friends, :contact
remove_method :attributes if method_defined?(:attributes) remove_method :attributes if method_defined?(:attributes)
def attributes def attributes
instance_values.except("address", "friends") instance_values.except("address", "friends", "contact")
end end
end end
...@@ -56,6 +56,9 @@ def setup ...@@ -56,6 +56,9 @@ def setup
@contact.address.zip = 11111 @contact.address.zip = 11111
@contact.address.apt_number = 35 @contact.address.apt_number = 35
@contact.friends = [Contact.new, Contact.new] @contact.friends = [Contact.new, Contact.new]
@related_contact = SerializableContact.new
@related_contact.name = "related"
@contact.contact = @related_contact
end end
test "should serialize default root" do test "should serialize default root" do
...@@ -256,4 +259,9 @@ def to_ary ...@@ -256,4 +259,9 @@ def to_ary
assert_match %r{<address>}, xml assert_match %r{<address>}, xml
assert_match %r{<apt-number type="integer">}, xml assert_match %r{<apt-number type="integer">}, xml
end end
test "association with sti" do
xml = @contact.to_xml(include: :contact)
assert xml.include?(%(<contact type="SerializableContact">))
end
end end
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册