【问题标题】:Add fields of a table to the parent table in serializers在序列化程序中将表的字段添加到父表
【发布时间】:2018-06-01 12:39:47
【问题描述】:

我有三个表用户、帖子和 cmets。 post的序列化器是

class PostSerializer < ActiveModel::Serializer
    attributes :id, :content, :like, :created_at, :updated_at
attributes :user
has_many :comments
def user
    object.user
end
end

评论有以下属性。评论序列化器是

class CommentSerializer < ActiveModel::Serializer
    attributes :id, :comment, :created_at, :updated_at
attributes :user
attributes :post
belongs_to :user
belongs_to :post
def user
  object.user
end
def post
  object.post
end
end

我在打印帖子的 JSON 时需要 cmets 的属性。

【问题讨论】:

    标签: json ruby-on-rails-5 active-model-serializers


    【解决方案1】:

    只需在PostSerializer 中的has_many 关联中传递serializer 选项

    改变

    has_many :comments

    has_many :comments, serializer: CommentSerializer

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-11
      • 1970-01-01
      • 1970-01-01
      • 2017-06-08
      • 1970-01-01
      • 1970-01-01
      • 2013-08-28
      • 2020-08-17
      相关资源
      最近更新 更多