我有一个像这样的Active Model Serializer类
class PostSerializer < ActiveModel::Serializer
attributes :activities
def activities
object.activities.each do |activity|
post_json(activity) if activity.class.name == 'Post'
like_json(activity) if activity.class.name == 'PostLike'
comments_json(activity) if activity.class.name == 'PostComment'
end
end
def post_json(post)
{
type: 'share',
user: post.user_id,
user_name: post.user.display_name,
user_image_thumb: post.user.profile.image.thumb.url,
id: post.id,
created_at: post.created_at
} if post
end
def like_json(like)
{
type: 'like',
user: like.user_id,
user_name: like.user.display_name,
user_image_thumb: like.user.profile.image.thumb.url,
id: like.id,
created_at: like.created_at
} if like
end
def comments_json(comment)
{
type: 'comment',
user: comment.user_id,
user_name: comment.user.display_name,
user_image_thumb: comment.user.profile.image.thumb.url,
id: comment.id,
created_at: comment.created_at,
content: comment.content
} if comment
end
end
但响应始终返回默认响应对象,并且不包含json构建器方法中的字段。
"activities": [
{
"id": 40,
"user_id": 22,
"post_id": 8,
"created_at": "2016-04-22T07:29:26.210Z",
"updated_at": "2016-04-22T07:29:26.210Z"
}
]
我该如何纠正这个?
答案 0 :(得分:1)
将each
更改为map
:
def activities
object.activities.map do |activity|
post_json(activity) if activity.class.name == 'Post'
like_json(activity) if activity.class.name == 'PostLike'
comments_json(activity) if activity.class.name == 'PostComment'
end
end