Reputation:
after setup the gem i've tried to get a deep nested polymorphic associated data.
but the gem just render the 1 level associated data.
the serializer
class CommentsSerializer < ActiveModel::Serializer
attributes :id, :title, :body, :user_id, :parent_id, :commentable_id, :commentable_type
belongs_to :user
belongs_to :commentable, :polymorphic => true
end
After some research
on the active_model_serializers github doc page
i've tried this solution, and did not worked either
has_many :commentable
def commentable
commentable = []
object.commentable.each do |comment|
commentable << { body: comment.body }
end
end
please someone can spare a tip on this issue?
and for some that should i use
ActiveModel::Serializer.config.default_includes = '**'
i've tried already this config too
The screeshot below illustrate this case
this comment has many reply's by commentable, but just render one. i would like to render the rest of comments of this comment.
Upvotes: 3
Views: 883
Reputation: 5313
You need to properly define your serializers and be careful not to render everything recursively. I have setup these 2 models:
class Post < ApplicationRecord
has_many :comments, as: :commentable
end
class Comment < ApplicationRecord
belongs_to :commentable, polymorphic: true
end
And these serializers:
class CommentSerializer < ActiveModel::Serializer
attributes :id, :body
belongs_to :commentable, serializer: CommentableSerializer
end
class CommentableSerializer < ActiveModel::Serializer
attributes :id, :body
has_many :comments, serializer: ShallowCommentSerializer
end
class ShallowCommentSerializer < ActiveModel::Serializer
attributes :id, :body
end
You need another serializer for all comments of a post, so that the comments don't try to render the post, which would try to render the comments, etc...
Keep your
ActiveModel::Serializer.config.default_includes = '**'
config option turned on.
Calling http://localhost:3000/comments/1
yields:
{
"id": 1,
"body": "comment",
"commentable": {
"id": 1,
"body": "post",
"comments": [
{
"id": 1,
"body": "comment"
},
{
"id": 2,
"body": "Reply comment"
}
]
}
}
which, I believe, is what you were trying to achieve.
Upvotes: 1