mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-25 07:16:49 +00:00
serialize_ids call methods on the corresponding serializer if defined
This commit is contained in:
@@ -454,6 +454,39 @@ class SerializerTest < ActiveModel::TestCase
|
||||
}, json)
|
||||
end
|
||||
|
||||
def test_methods_take_priority_over_associations_and_call_the_appropriate_id_method
|
||||
comment_serializer = Class.new(ActiveModel::Serializer) do
|
||||
def id
|
||||
"OMG"
|
||||
end
|
||||
end
|
||||
|
||||
post_serializer = Class.new(ActiveModel::Serializer) do
|
||||
attributes :title
|
||||
has_many :comments, :serializer => comment_serializer
|
||||
embed :ids
|
||||
|
||||
def comments
|
||||
object.comments[0,1]
|
||||
end
|
||||
end
|
||||
|
||||
post = Post.new(:title => "My Post")
|
||||
comments = [Comment.new(:title => "Comment1", :id => 1), Comment.new(:title => "Comment2", :id => 2)]
|
||||
post.comments = comments
|
||||
|
||||
post.class_eval do
|
||||
define_method :comment_ids, lambda {
|
||||
self.comments.map { |c| c.read_attribute_for_serialization(:id) }
|
||||
}
|
||||
end
|
||||
json = post_serializer.new(post).as_json
|
||||
assert_equal({
|
||||
:title => "My Post",
|
||||
:comment_ids => ["OMG"]
|
||||
}, json)
|
||||
end
|
||||
|
||||
def test_embed_objects
|
||||
serializer = post_serializer
|
||||
|
||||
@@ -684,6 +717,42 @@ class SerializerTest < ActiveModel::TestCase
|
||||
}, hash.as_json)
|
||||
end
|
||||
|
||||
def test_embed_id_for_has_one_overriding_associated_id
|
||||
author_serializer = Class.new(ActiveModel::Serializer) do
|
||||
def id
|
||||
"OMG"
|
||||
end
|
||||
end
|
||||
|
||||
serializer_class = Class.new(ActiveModel::Serializer) do
|
||||
embed :ids
|
||||
root :post
|
||||
|
||||
attributes :title, :body
|
||||
has_one :author, :serializer => author_serializer
|
||||
end
|
||||
|
||||
post_class = Class.new(Model) do
|
||||
attr_accessor :author
|
||||
end
|
||||
|
||||
author_class = Class.new(Model)
|
||||
|
||||
post = post_class.new(:title => "New Post", :body => "It's a new post!")
|
||||
author = author_class.new(:id => 5)
|
||||
post.author = author
|
||||
|
||||
hash = serializer_class.new(post)
|
||||
|
||||
assert_equal({
|
||||
:post => {
|
||||
:title => "New Post",
|
||||
:body => "It's a new post!",
|
||||
:author_id => "OMG"
|
||||
}
|
||||
}, hash.as_json)
|
||||
end
|
||||
|
||||
def test_embed_objects_for_has_one
|
||||
author_serializer = Class.new(ActiveModel::Serializer) do
|
||||
attributes :id, :name
|
||||
|
||||
Reference in New Issue
Block a user