【发布时间】:2018-05-26 08:24:30
【问题描述】:
我使用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
}
]
}
【问题讨论】:
标签: ruby-on-rails associations active-model-serializers