ruby-on-railsdynamicworkflowcancanacts-as-state-machine

Creating a dynamic approval system in Rails


I am trying to figure out how to implement a dynamic approval system in Rails. The scenario is this: I have a model object (a document) which, when created, the user can assign an approval flow to. The document can be filled and submitted by a user. The document then goes through the approval flow before being "approved".

For example, let's say I create a "leave request" document. As a user I can then claim that the leave request must be approved by my line manager and someone from HR before being in the state "approved".

I have explored using a number of state-machine gems and CanCan for permissions, but I cannot wrap my head around how to dynamically create these workflows. I thought about serializing the workflow in the database, but this means that every time I want to determine a document approvers list of documents awaiting approval I will have to deserialize every workflow in the list of documents in the "awaiting approval" state.

Has anyone got any ideas as to how to tackle this problem?


Solution

  • I think the best solution is to use separate table for storing approvers. You can dynamicly create 'approvers' when you create a document and then change each 'approver' independing of others. A document is approved if it does not have unapproved 'approvers'.

    class Approver < ActiveRecord::Base
      attr_accessible :approved, role, ...
      # where role is manager or someone from HR or ...
      # approved is a status (true or false)
    
      belongs_to :document
      ...
    end
    
    class Document < ActiveRecord::Base
      has_many :approvers
    
      def approved?
        approvers.where(approved: false).empty?
      end
    
      ....
    end