我使用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
我得到这样的回应:
响应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"
}
]
}
}
}
}
如果我删除has_many :responses
from QuestionSerializer
我明白了:
响应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"
}
}
}
我如何有条件的得到任一响应1 or 响应2在运行时?我尝试了找到的所有建议 - 都不适用于 AMS 0.10.2。目前,该条件仅以这种方式起作用:
class QuestionSerializer < ActiveModel::Serializer
attributes :id, :title, :created_at, :updated_at
has_many :responses if true
end
OR:
class QuestionSerializer < ActiveModel::Serializer
attributes :id, :title, :created_at, :updated_at
has_many :responses if false
end
在这两种情况下我真的得到了响应1 or 响应2。但这是硬编码的,我想将参数传递到序列化器中或做一些类似的事情。
我应该怎么办?