如何从活动模型序列化中的关联模型中提取数据?
How to pull data from associative models in active model serializes?
我正在使用 active_model_serializers
gem 将响应发送为 JSON
。
我从关联模型中提取数据,但如何仅从 questions
table 获取那些数据,其中 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
}
]
}
您可以通过自己定义 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
我正在使用 active_model_serializers
gem 将响应发送为 JSON
。
我从关联模型中提取数据,但如何仅从 questions
table 获取那些数据,其中 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
}
]
}
您可以通过自己定义 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