I have a workflow
model and 2 types of workflows
- normal_workflow
- 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:
NormalWorkflow
has to show only a subset of all the field ofWorkflow
with some meta information.SpecialWorkflow
has to show a different subset of the fields ofWorkflow
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)