我如何 select 我想要活动模型序列化程序关系的哪些属性

How do I select which attributes I want for active model serializers relationships

我正在使用 JSONAPI format along with Active Model Serializers to create an api with rails-api

我有一个序列化程序,它显示一个特定的 post,其中有许多 topics,目前,在关系下,列出了这些主题。它目前只列出了 id 和类型。我也想显示主题的标题。

有人会说在我的控制器中使用 include: '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

我试过的一件事 - 下面有一个答案使这项工作有效,但这并不是我真正想要的。

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

  belongs_to :domain
  belongs_to :user

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

只需确保 return 哈希或哈希数组,如下所示:

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

与其定义主题方法,不如定义单独的主题序列化程序,并明确指定您需要包含哪些属性。这是比定义主题方法更清晰、更易于维护的方法。

class PostSerializer < ActiveModel::Serializer
  attributes :title

  belongs_to :domain
  belongs_to :user
  # remember to declare TopicSerializer class before you use it
  class TopicSerializer < ActiveModel::Serializer
    # explicitly tell here which attributes you need from 'topics'
    attributes :title
  end
  has_many :topics, serializer: TopicSerializer
end

同样,尽量避免为关系定义方法,它不干净,也不可维护。