📦 closure_tree/ ClosureTree
Easily and efficiently make your ActiveRecord models support hierarchies
Установка и запуск
Installation
Note that closure_tree only supports ActiveRecord 7.2 and later, and has test coverage for MySQL, PostgreSQL, and SQLite.
-
Add
gem 'closure_tree'to your Gemfile -
Run
bundle install -
Add
has_closure_tree(oracts_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 endMake sure you check out the large number of options that
has_closure_treeaccepts.Note: The
acts_as_treealias is only created if your model doesn't already have a method with that name. This prevents conflicts with other gems like the originalacts_as_treegem.IMPORTANT: Make sure you add
has_closure_treeafterattr_accessibleandself.table_name =lines in your model.If you're already using other hierarchical gems, like
ancestryoracts_as_tree, please refer to the warning section! -
Add a migration to add a
parent_idcolumn 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 endThe column must be nullable. Root nodes have a
NULLparent_id. -
Run
rails g closure_tree:migration tag(and replacetagwith 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