我正在使用JSONAPI格式随着主动模型序列化器创建一个 apiRails API.
我有一个序列化器,它显示特定的post
那有很多topics
目前,在关系下列出了这些主题。目前它只列出了 id 和类型。我也想显示主题的标题。
有人会说用include: 'topics'
在我的控制器中,但我不需要完整的主题记录,只需要它的标题。
Question:如何指定要显示主题的哪些属性?
我拥有的
"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