TreeStructure

Tree Structure allows the records of a ActiveRecord model to be organized in a tree structure.

Installation

Add this line to your application's Gemfile:

gem 'tree_structure'

And then execute:

$ bundle install

Or install it yourself as:

$ gem install tree_structure

Development

After installing the tree_structure gem in your Gemfile, follow these steps to set up the tree structure:

  1. Add a parent_id column to the table where you want to organize the tree structure. You can do this by creating a migration:

    class AddParentIdToYourModel < ActiveRecord::Migration[6.0]
      def change
        add_column :your_model_name, :parent_id, :integer
        add_index :your_model_name, :parent_id
      end
    end
    
  2. Include the TreeStructure module in the model that will be organized in a tree structure. For example:

    class YourModelName < ApplicationRecord
      include TreeStructure
    end
    
  3. Run your migrations to update the database schema:

    rails db:migrate
    

Example Usage

Once you have set up your model, you can start using the tree structure features. For example:

Create root nodes

root1 = YourModelName.create(name: 'Root 1')
root2 = YourModelName.create(name: 'Root 2')

Create child nodes

child1 = YourModelName.create(name: 'Child 1', parent: root1)
child2 = YourModelName.create(name: 'Child 2', parent: root1)
child3 = YourModelName.create(name: 'Child 3', parent: root2)

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/tree_structure.

License

The gem is available as open source under the terms of the MIT License.