Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forced Binary Matrix company structure implementation in Rails

I'm working on a Rails project that models the structure of a company with a binary matrix plan schema. Each new user is 'placed' in the hierarchy as shown here:

User insertion algorithm

There is no balancing and all levels must be filled before moving to the next one. Only the order of insertion matters when inserting newcomers. Our database system is Postgres.

I was planning to use some gem to help me with the tree implementation (Closure Tree is a firm candidate) but I'm not sure on how to approach the constraints (insertion, deletion) of this 'forced binary tree from left to right' model.

I'm trying to figure all this out, but since I've never been involved in such implementations (specially involving databases) I thought I could use some help from more experienced programmers on common pitfalls or where should I put special attention. The user base is expected to grow quite quickly so I'm worried about performance.

So my questions:

  • Since I'm stuck to a relational database, what would be the best way to model this schema?
  • Is there any documentation or gem that I can dig into to learn the best way to implement all the algorithms that I will need?

Thanks in advance for any tips/pointers.

like image 351
Janko Avatar asked Nov 10 '22 05:11

Janko


1 Answers

Here is the solution that worked for me.

  1. Create your rails app and specify Postgresql as the database.

  2. Add the acts_as_sane_tree gem to your gemfile.

  3. Generate a model for your users with a parent_id column as the foreign key.

  4. The database migration file should look something like this

    class CreateUsers < ActiveRecord::Migration[5.0]
      def change
        create_table :users do |t|
          t.string :name
          t.integer :parent_id
          t.timestamps
        end
      end
    end
    
  5. Your model should have the following method:

    class User < ApplicationRecord
        acts_as_sane_tree :order => "name"
    end
    

You can find more information from the following links:

https://github.com/chrisroberts/acts_as_sane_tree

http://www.gmarik.info/blog/2012/recursive-data-structures-with-rails/

like image 127
Femchengdu Avatar answered Nov 14 '22 22:11

Femchengdu