【发布时间】:2015-09-29 21:24:23
【问题描述】:
我正在使用JSONAPI format 和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"
}
]
}
}
}
我想要什么
"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
【问题讨论】:
标签: ruby-on-rails json active-model-serializers rails-api