如何从活动模型序列化中的关联模型中提取数据?

时间:2018-05-26 08:24:31

标签: ruby-on-rails associations active-model-serializers

我正在使用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
        }
    ]
}

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