简体   繁体   中英

Rails active_model_serializers on polymorphic nested association

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM