Search code examples
ruby-on-railsassociationsactive-model-serializers

How to pull data from associative models in active model serializes?


I'm using active_model_serializers gem to send response as JSON. I pull the data from association models but how to get only those data from questions table where UserType equals to clients.UserType.

ClientSerializer:

class ClientSerializer < ActiveModel::Serializer
  attributes :id, :username, :access_token, :UserType

  has_many :questions, include: :all
end

and QuestionSerializer:

class QuestionSerializer < ActiveModel::Serializer
  attributes :id, :question, :client_id, :UserType
  belongs_to :user
end

here is the output as 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
        }
    ]
}

Expected Output 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
        }
    ]
}

Solution

  • You can achieve this by defining the questions method yourself and fetch scoped questions in it:

    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