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:
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:
Thanks in advance for any tips/pointers.
Here is the solution that worked for me.
Create your rails app and specify Postgresql as the database.
Add the acts_as_sane_tree gem to your gemfile.
Generate a model for your users with a parent_id column as the foreign key.
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
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With