к каталогу

📦 closure_tree/ ClosureTree

Easily and efficiently make your ActiveRecord models support hierarchies

Открыть на GitHubобновлён 2нед назад
Звёзды
1.9k
Форки
248
За неделю
За месяц
Рост %
Язык
Ruby

Установка и запуск

Installation

Note that closure_tree only supports ActiveRecord 7.2 and later, and has test coverage for MySQL, PostgreSQL, and SQLite.

  1. Add gem 'closure_tree' to your Gemfile

  2. Run bundle install

  3. Add has_closure_tree (or acts_as_tree, which is an alias of the same method) to your hierarchical model:

    class Tag < ApplicationRecord
      has_closure_tree
    end
    
    class AnotherTag < ApplicationRecord
      acts_as_tree
    end
    

    Make sure you check out the large number of options that has_closure_tree accepts.

    Note: The acts_as_tree alias is only created if your model doesn't already have a method with that name. This prevents conflicts with other gems like the original acts_as_tree gem.

    IMPORTANT: Make sure you add has_closure_tree after attr_accessible and self.table_name = lines in your model.

    If you're already using other hierarchical gems, like ancestry or acts_as_tree, please refer to the warning section!

  4. Add a migration to add a parent_id column to the hierarchical model. You may want to also add a column for deterministic ordering of children, but that's optional.

    class AddParentIdToTag < ActiveRecord::Migration[7.2]
      def change
        add_column :tags, :parent_id, :integer
      end
    end
    

    The column must be nullable. Root nodes have a NULL parent_id.

  5. Run rails g closure_tree:migration tag (and replace tag with your model name) to create the closure tree table for your model.

Run with PostgreSQL

DATABASE_URL=postgres://localhost/closure_tree_test rake test

Run with MySQL

DATABASE_URL=mysql2://localhost/closure_tree_test rake test

Из README репозитория · полный README на GitHub

Теги

activerecordancestrychildclosure-treedescendantshierarchieshierarchynested-hashesnested-setparentrailsrubytree-structure