【发布时间】:2017-02-15 08:33:28
【问题描述】:
我使用 rails (5.0.1) 和 active_model_serializers (0.10.2)。我想以某种方式有条件地序列化has_many 关联:
class Question < ApplicationRecord
has_many :responses, :inverse_of => :question
end
class Response < ApplicationRecord
belongs_to :question, :inverse_of => :responses
end
class QuestionSerializer < ActiveModel::Serializer
attributes :id, :title, :created_at, :updated_at
has_many :responses
end
class ResponseSerializer < ActiveModel::Serializer
attributes :id, :title
end
我使用 jsonapi 并查询 http://localhost:3000/api/questions/1 我得到这个回复:
Response-1:
{
"data": {
"id": "1",
"type": "questions",
"attributes": {
"title": "First",
"created-at": "2017-02-14T09:49:20.148Z",
"updated-at": "2017-02-14T13:55:37.365Z"
},
"relationships": {
"responses": {
"data": [
{
"id": "1",
"type": "responses"
}
]
}
}
}
}
如果我从QuestionSerializer 中删除has_many :responses,我会得到:
响应 2:
{
"data": {
"id": "1",
"type": "questions",
"attributes": {
"title": "First",
"created-at": "2017-02-14T09:49:20.148Z",
"updated-at": "2017-02-14T13:55:37.365Z"
}
}
}
我如何有条件地在运行时获得 Response-1 或 Response-2?我尝试了所有找到的建议 - 都不适用于 AMS 0.10.2。目前,该条件仅以这种方式起作用:
class QuestionSerializer < ActiveModel::Serializer
attributes :id, :title, :created_at, :updated_at
has_many :responses if true
end
或者:
class QuestionSerializer < ActiveModel::Serializer
attributes :id, :title, :created_at, :updated_at
has_many :responses if false
end
在这两种情况下,我确实得到了 Response-1 或 Response-2。但这是硬编码的,我想可能将参数传递给序列化程序或做一些类似的事情。
我该怎么办?
【问题讨论】:
标签: ruby-on-rails active-model-serializers