【问题标题】:How to pull data from associative models in active model serializes?如何从活动模型序列化中的关联模型中提取数据?
【发布时间】: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


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-14
      相关资源
      最近更新 更多