mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-22 22:06:50 +00:00
only the associated objects of the last object in the collection will actually show up in the serialized data. For example, if you serialize a collection of two posts, each containing one or more comments, only the comments of the last post show up. The reason is a Hash#merge wich overwrites the array rather than appending to it. This commit fixes this by merging the collection arrays, rather than the top-level hashes.
67 lines
1.1 KiB
Ruby
67 lines
1.1 KiB
Ruby
class Model
|
|
def initialize(hash={})
|
|
@attributes = hash
|
|
end
|
|
|
|
def read_attribute_for_serialization(name)
|
|
if name == :id || name == 'id'
|
|
object_id
|
|
else
|
|
@attributes[name]
|
|
end
|
|
end
|
|
end
|
|
|
|
|
|
###
|
|
## Models
|
|
###
|
|
class User < Model
|
|
def profile
|
|
@profile ||= Profile.new(name: 'N1', description: 'D1')
|
|
end
|
|
end
|
|
|
|
class Profile < Model
|
|
end
|
|
|
|
class Post < Model
|
|
attr_writer :comments
|
|
|
|
def comments
|
|
@comments ||= [Comment.new(content: 'C1'),
|
|
Comment.new(content: 'C2')]
|
|
end
|
|
end
|
|
|
|
class Comment < Model
|
|
end
|
|
|
|
###
|
|
## Serializers
|
|
###
|
|
class UserSerializer < ActiveModel::Serializer
|
|
attributes :name, :email
|
|
|
|
has_one :profile
|
|
end
|
|
|
|
class ProfileSerializer < ActiveModel::Serializer
|
|
def description
|
|
description = object.read_attribute_for_serialization(:description)
|
|
scope ? "#{description} - #{scope}" : description
|
|
end
|
|
|
|
attributes :name, :description
|
|
end
|
|
|
|
class PostSerializer < ActiveModel::Serializer
|
|
attributes :title, :body
|
|
|
|
has_many :comments
|
|
end
|
|
|
|
class CommentSerializer < ActiveModel::Serializer
|
|
attributes :content
|
|
end
|