我正在使用active_model_serializers
gem将回复发送为JSON
。
我从关联模型中提取数据,但是如何仅从questions
表中获取UserType
等于clients.UserType
的数据。
ClientSerializer
:
class ClientSerializer < ActiveModel::Serializer
attributes :id, :username, :access_token, :UserType
has_many :questions, include: :all
end
和QuestionSerializer
:
class QuestionSerializer < ActiveModel::Serializer
attributes :id, :question, :client_id, :UserType
belongs_to :user
end
此处输出为JSON
:
{
"id": 4,
"username": "171fdkjgku",
"access_token": "77NVccAJG7hEKSGQUcKkSip5",
"UserType": 1,
"questions": [
{
"id": 1,
"question": "Lorem Ipsum",
"client_id": 4,
"UserType": 1
},
{
"id": 2,
"question": "Lorem Ipsum 2",
"client_id": 4,
"UserType": 0
},
{
"id": 3,
"question": "Lorem Ipsum 3",
"client_id": 4,
"UserType": 1
}
]
}
预期输出JSON
:
{
"id": 4,
"username": "171fdkjgku",
"access_token": "77NVccAJG7hEKSGQUcKkSip5",
"UserType": 1,
"questions": [
{
"id": 1,
"question": "Lorem Ipsum",
"client_id": 4,
"UserType": 1
},
{
"id": 3,
"question": "Lorem Ipsum 3",
"client_id": 4,
"UserType": 1
}
]
}
答案 0 :(得分:1)
您可以通过自己定义questions
方法并在其中获取范围问题来实现此目的:
class ClientSerializer < ActiveModel::Serializer
attributes :id, :username, :access_token, :UserType, :questions
def questions
ques = self.object.questions.where(UserType: self.object.UserType).to_a
ActiveModel::ArraySerializer.new(ques, each_serializer: QuestionSerializer).as_json
end
end