I have a Active Model Serializer class like this
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
But the response always returns the default response object and doesnot contain the fields from the json builder methods.
"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"
}
]
How can I rectify this?
Change each
to 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