mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-24 14:56:50 +00:00
Support serialize polymorphic id
This commit is contained in:
parent
32f8779114
commit
7e96856b87
@ -245,7 +245,11 @@ module ActiveModel
|
|||||||
end
|
end
|
||||||
|
|
||||||
def serialize_ids
|
def serialize_ids
|
||||||
if object = associated_object
|
object = associated_object
|
||||||
|
|
||||||
|
if object && polymorphic?
|
||||||
|
{ polymoprhic_key => object.read_attribute_for_serialization(:id) }
|
||||||
|
elsif object
|
||||||
object.read_attribute_for_serialization(:id)
|
object.read_attribute_for_serialization(:id)
|
||||||
else
|
else
|
||||||
nil
|
nil
|
||||||
|
|||||||
@ -999,4 +999,40 @@ class SerializerTest < ActiveModel::TestCase
|
|||||||
}
|
}
|
||||||
}, actual)
|
}, actual)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def test_can_handle_polymoprhic_ids
|
||||||
|
email_serializer = Class.new(ActiveModel::Serializer) do
|
||||||
|
attributes :subject, :body
|
||||||
|
end
|
||||||
|
|
||||||
|
email_class = Class.new(Model) do
|
||||||
|
def self.to_s
|
||||||
|
"Email"
|
||||||
|
end
|
||||||
|
|
||||||
|
define_method :active_model_serializer do
|
||||||
|
email_serializer
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
attachment_serializer = Class.new(ActiveModel::Serializer) do
|
||||||
|
embed :ids
|
||||||
|
attributes :name, :url
|
||||||
|
has_one :attachable, :polymorphic => true
|
||||||
|
end
|
||||||
|
|
||||||
|
email = email_class.new :id => 1
|
||||||
|
|
||||||
|
attachment = Attachment.new :name => 'logo.png', :url => 'http://example.com/logo.png', :attachable => email
|
||||||
|
|
||||||
|
actual = attachment_serializer.new(attachment, {}).as_json
|
||||||
|
|
||||||
|
assert_equal({
|
||||||
|
:name => 'logo.png',
|
||||||
|
:url => 'http://example.com/logo.png',
|
||||||
|
:attachable => {
|
||||||
|
:email => 1
|
||||||
|
}
|
||||||
|
}, actual)
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user