如何为活动模型序列化程序关系选择所需的属性

ala*_*ter 8 json ruby-on-rails rails-api active-model-serializers

我使用JSONAPI格式Active Model Serializers来创建带有rails-api的api.

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

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

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

是)我有的

"data": {
  "id": "26",
  "type": "posts",
  "attributes": {
    "title": "Test Title 11"
  },
  "relationships": {
    "topics": {
      "data": [
        {
          "id": "1",
          "type": "topics"
        }
      ]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我想要的是

"data": {
  "id": "26",
  "type": "posts",
  "attributes": {
    "title": "Test Title 11"
  },
  "relationships": {
    "topics": {
      "data": [
        {
          "id": "1",
          "type": "topics",
          "title": "Topic Title"
        }
      ]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我目前的序列化程序类编辑:这就是我想要的.

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
Run Code Online (Sandbox Code Playgroud)

我试过的一件事 - 下面有一个答案可以使这个工作,但它不是我真正想要的.

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

  belongs_to :domain
  belongs_to :user

  def topics
    # THIS WAS ANSWERED BELOW! THANK YOU
  end
end
Run Code Online (Sandbox Code Playgroud)

pen*_*ner 7

只需确保返回散列或散列数组,如下所示:

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
Run Code Online (Sandbox Code Playgroud)