如何为活动模型序列化程序关系选择所需的属性 [英] How do I select which attributes I want for active model serializers relationships

查看:140
本文介绍了如何为活动模型序列化程序关系选择所需的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 JSONAPI格式我有一个序列化程序,该序列化程序显示具有许多topics的特定post,当前在关系下列出了这些主题.当前仅列出ID和类型.我也想显示该主题的标题.

I have a serializer which shows a specific post that has many topics and currently, under relationships, lists those topics. It currently only lists the id and type. I want to show the title of the topic as well.

有人会说要在控制器中使用include: 'topics',但是我不需要完整的主题记录,而只是标题.

Some would say to use include: 'topics' in my controller, but I don't need the full topic record, just its title.

问题:如何指定要从主题中显示的属性?

Question: How do I specify which attributes I want to show from topics?

我有什么

"data": {
  "id": "26",
  "type": "posts",
  "attributes": {
    "title": "Test Title 11"
  },
  "relationships": {
    "topics": {
      "data": [
        {
          "id": "1",
          "type": "topics"
        }
      ]
    }
  }
}

我想要的

"data": {
  "id": "26",
  "type": "posts",
  "attributes": {
    "title": "Test Title 11"
  },
  "relationships": {
    "topics": {
      "data": [
        {
          "id": "1",
          "type": "topics",
          "title": "Topic Title"
        }
      ]
    }
  }
}

我当前的序列化程序类这是我所需要的.

class PostSerializer < ActiveModel::Serializer
  attributes :title

  belongs_to :domain
  belongs_to :user

  has_many :topics, serializer: TopicSerializer

  def topics
    # THIS IS WHAT I AM REALLY ASKING FOR
  end
end

class TopicSerializer < ActiveModel::Serializer
  attributes :title, :description

  belongs_to :parent
  has_many :children
end

我尝试过的一件事-下面有一个答案可以使这项工作奏效,但并不是我真正追求的.

One thing I tried - there is an answer below that makes this work, but its not really what I'm after.

class PostSerializer < ActiveModel::Serializer
  attributes :title, :topics

  belongs_to :domain
  belongs_to :user

  def topics
    # THIS WAS ANSWERED BELOW! THANK YOU
  end
end

推荐答案

只需确保像这样返回哈希或哈希数组:

Just make sure to return a hash or array of hashes like so:

def videos
    object.listing_videos.collect do |lv|
      {
        id: lv.video.id,
        name: lv.video.name,
        wistia_id: lv.video.wistia_id,
        duration: lv.video.duration,
        wistia_hashed_id: lv.video.wistia_hashed_id,
        description: lv.video.description,
        thumbnail: lv.video.thumbnail
      }
    end
  end

这篇关于如何为活动模型序列化程序关系选择所需的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆