Jasjeet Singh
Jasjeet Singh

Reputation: 332

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

Upvotes: 0

Views: 59

Answers (1)

Jagdeep Singh
Jagdeep Singh

Reputation: 4920

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

Upvotes: 1

Related Questions