2

I have a workflow model and 2 types of workflows

  1. normal_workflow
  2. special_workflow

There is a project model which is related to the workflow model using has_many/belongs_to association.

Now for getting all the workflows of a project, we have a WorkflowsController.

I wanted to return an array of workflows (which in this would include 2 records, one for normal_workflow and another one for special_workflow) with the following requirements:

  1. NormalWorkflow has to show only a subset of all the field of Workflow with some meta information.
  2. SpecialWorkflow has to show a different subset of the fields of Workflow with some meta.

One way of achieving that is to check the type of workflow for each attribute and relationship. I think this approach is not that good, because when the type of workflow gets increased the conditionals in the serializer would also increase.

class Project
    has_many :workflows
    has_many :normal_workflows
    has_many :special_workflows
end

class Workflow < ApplicationRecord
    belongs_to :project
end

class NormalWorkflow < Workflow
    # STI model
    belongs_to :project
end

class SpecialWorkflow < Workflow
    # STI model
    belongs_to :project
end

class WorkflowsController < ApplicationController
    # Using fast-json-api gem
    def index
        @workflows = WorkflowSerializer.new(@project.workflows).serialize_json
    end
end

So, I am looking for a cleaner solution which will help to keep the code DRY and also bit extensible for other types. (It might be using some decorators or any other object)

Vivek Tiwary
  • 180
  • 1
  • 9
  • 2
    For AMS, you may take some hint from https://github.com/rails-api/active_model_serializers/issues/2138#issuecomment-335861516 – Wasif Hossain Feb 12 '19 at 13:21

0 Answers0