{"id":25175078,"url":"https://github.com/mediafellows/ancestry","last_synced_at":"2025-04-04T00:44:52.696Z","repository":{"id":114546077,"uuid":"254134425","full_name":"mediafellows/ancestry","owner":"mediafellows","description":" Organise ActiveRecord model into a tree structure (fork with modifications in allow-string-ids branch)","archived":false,"fork":false,"pushed_at":"2020-04-08T16:04:12.000Z","size":8740,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":7,"default_branch":"master","last_synced_at":"2025-02-09T12:31:59.308Z","etag":null,"topics":["fork","library"],"latest_commit_sha":null,"homepage":"https://github.com/stefankroes/ancestry","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mediafellows.png","metadata":{"files":{"readme":"README.rdoc","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"MIT-LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-04-08T15:58:20.000Z","updated_at":"2020-04-08T16:11:13.000Z","dependencies_parsed_at":null,"dependency_job_id":"ed931883-3a76-4290-803c-d17d423b809a","html_url":"https://github.com/mediafellows/ancestry","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mediafellows%2Fancestry","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mediafellows%2Fancestry/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mediafellows%2Fancestry/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mediafellows%2Fancestry/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mediafellows","download_url":"https://codeload.github.com/mediafellows/ancestry/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247103299,"owners_count":20884023,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["fork","library"],"created_at":"2025-02-09T12:28:47.444Z","updated_at":"2025-04-04T00:44:52.682Z","avatar_url":"https://github.com/mediafellows.png","language":"Ruby","funding_links":[],"categories":[],"sub_categories":[],"readme":"{\u003cimg src=\"https://travis-ci.org/stefankroes/ancestry.png?branch=master\" alt=\"Build Status\" /\u003e}[https://travis-ci.org/stefankroes/ancestry]\n{\u003cimg src=\"https://coveralls.io/repos/stefankroes/ancestry/badge.png\" alt=\"Coverage Status\" /\u003e}[https://coveralls.io/r/stefankroes/ancestry]\n\n= Ancestry\n\nAncestry is a gem/plugin that allows the records of a Ruby on Rails ActiveRecord model to be organised as a tree structure (or hierarchy). It uses a single, intuitively formatted database column, using a variation on the materialised path pattern. It exposes all the standard tree structure relations (ancestors, parent, root, children, siblings, descendants) and all of them can be fetched in a single SQL query. Additional features are STI support, scopes, depth caching, depth constraints, easy migration from older plugins/gems, integrity checking, integrity restoration, arrangement of (sub)tree into hashes and different strategies for dealing with orphaned records.\n\n= Installation\n\nTo apply Ancestry to any ActiveRecord model, follow these simple steps:\n\n1. Install\n   - \u003cb\u003eRails 2\u003c/b\u003e\n     - See 1-3-stable branch\n   - \u003cb\u003eRails 3\u003c/b\u003e\n     - Add to Gemfile: \u003cb\u003egem 'ancestry'\u003c/b\u003e\n     - Install required gems: \u003cb\u003ebundle install\u003c/b\u003e\n\n2. Add ancestry column to your table\n   - Create migration: \u003cb\u003erails g migration add_ancestry_to_[table] ancestry:string\u003c/b\u003e\n   - Add index to migration: \u003cb\u003eadd_index [table], :ancestry\u003c/b\u003e (UP) / \u003cb\u003eremove_index [table], :ancestry\u003c/b\u003e (DOWN)\n   - Migrate your database: \u003cb\u003erake db:migrate\u003c/b\u003e\n\n3. Add ancestry to your model\n   - Add to app/models/[model].rb: \u003cb\u003ehas_ancestry\u003c/b\u003e\n\nYour model is now a tree!\n\n= Using acts_as_tree instead of has_ancestry\n\nIn version 1.2.0 the \u003cb\u003eacts_as_tree\u003c/b\u003e method was \u003cb\u003erenamed to has_ancestry\u003c/b\u003e in order to allow usage of both the acts_as_tree gem and the ancestry gem in a single application. To not break backwards compatibility, the has_ancestry method is aliased with acts_as_tree if ActiveRecord::Base does not respond to acts_as_tree. acts_as_tree will continue to be supported in the future as I personally prefer it.\n\n= Organising records into a tree\n\nYou can use the parent attribute to organise your records into a tree. If you have the id of the record you want to use as a parent and don't want to fetch it, you can also use parent_id. Like any virtual model attributes, parent and parent_id can be set using parent= and parent_id= on a record or by including them in the hash passed to new, create, create!, update_attributes and update_attributes!. For example:\n\n  TreeNode.create! :name =\u003e 'Stinky', :parent =\u003e TreeNode.create!(:name =\u003e 'Squeeky')\n\nYou can also create children through the children relation on a node:\n\n  node.children.create :name =\u003e 'Stinky'\n\n= Navigating your tree\n\nTo navigate an Ancestry model, use the following methods on any instance / record:\n\n  parent           Returns the parent of the record, nil for a root node\n  parent_id        Returns the id of the parent of the record, nil for a root node\n  root             Returns the root of the tree the record is in, self for a root node\n  root_id          Returns the id of the root of the tree the record is in\n  root?, is_root?  Returns true if the record is a root node, false otherwise\n  ancestor_ids     Returns a list of ancestor ids, starting with the root id and ending with the parent id\n  ancestors        Scopes the model on ancestors of the record\n  path_ids         Returns a list the path ids, starting with the root id and ending with the node's own id\n  path             Scopes model on path records of the record\n  children         Scopes the model on children of the record\n  child_ids        Returns a list of child ids\n  has_children?    Returns true if the record has any children, false otherwise\n  is_childless?    Returns true is the record has no children, false otherwise\n  siblings         Scopes the model on siblings of the record, the record itself is included\n  sibling_ids      Returns a list of sibling ids\n  has_siblings?    Returns true if the record's parent has more than one child\n  is_only_child?   Returns true if the record is the only child of its parent\n  descendants      Scopes the model on direct and indirect children of the record\n  descendant_ids   Returns a list of a descendant ids\n  subtree          Scopes the model on descendants and itself\n  subtree_ids      Returns a list of all ids in the record's subtree\n  depth            Return the depth of the node, root nodes are at depth 0\n\n= Options for has_ancestry\n\nThe has_ancestry methods supports the following options:\n\n  :ancestry_column       Pass in a symbol to store ancestry in a different column\n  :orphan_strategy       Instruct Ancestry what to do with children of a node that is destroyed:\n                         :destroy   All children are destroyed as well (default)\n                         :rootify   The children of the destroyed node become root nodes\n                         :restrict  An AncestryException is raised if any children exist\n                         :adopt     The orphan subtree is added to the parent of the deleted node.\n                                    If the deleted node is Root, then rootify the orphan subtree.\n  :cache_depth           Cache the depth of each node in the 'ancestry_depth' column (default: false)\n                         If you turn depth_caching on for an existing model:\n                         - Migrate: add_column [table], :ancestry_depth, :integer, :default =\u003e 0\n                         - Build cache: TreeNode.rebuild_depth_cache!\n  :depth_cache_column    Pass in a symbol to store depth cache in a different column\n  :primary_key_format    Supply a regular expression that matches the format of your primary key.\n                         By default, primary keys only match integers ([0-9]+).\n  :touch                 Instruct Ancestry to touch the ancestors of a node when it changes, to\n                         invalidate nested key-based caches. (default: false)\n\n= (Named) Scopes\n\nWhere possible, the navigation methods return scopes instead of records, this means additional ordering, conditions, limits, etc. can be applied and that the result can be either retrieved, counted or checked for existence. For example:\n\n  node.children.exists?(:name =\u003e 'Mary')\n  node.subtree.all(:order =\u003e :name, :limit =\u003e 10).each do; ...; end\n  node.descendants.count\n\nFor convenience, a couple of named scopes are included at the class level:\n\n  roots                   Root nodes\n  ancestors_of(node)      Ancestors of node, node can be either a record or an id\n  children_of(node)       Children of node, node can be either a record or an id\n  descendants_of(node)    Descendants of node, node can be either a record or an id\n  subtree_of(node)        Subtree of node, node can be either a record or an id\n  siblings_of(node)       Siblings of node, node can be either a record or an id\n\nThanks to some convenient rails magic, it is even possible to create nodes through the children and siblings scopes:\n\n  node.children.create\n  node.siblings.create!\n  TestNode.children_of(node_id).new\n  TestNode.siblings_of(node_id).create\n\n= Selecting nodes by depth\n\nWhen depth caching is enabled (see has_ancestry options), five more named scopes can be used to select nodes on their depth:\n\n  before_depth(depth)     Return nodes that are less deep than depth (node.depth \u003c depth)\n  to_depth(depth)         Return nodes up to a certain depth (node.depth \u003c= depth)\n  at_depth(depth)         Return nodes that are at depth (node.depth == depth)\n  from_depth(depth)       Return nodes starting from a certain depth (node.depth \u003e= depth)\n  after_depth(depth)      Return nodes that are deeper than depth (node.depth \u003e depth)\n\nThe depth scopes are also available through calls to descendants, descendant_ids, subtree, subtree_ids, path and ancestors. In this case, depth values are interpreted relatively. Some examples:\n\n  node.subtree(:to_depth =\u003e 2)      Subtree of node, to a depth of node.depth + 2 (self, children and grandchildren)\n  node.subtree.to_depth(5)          Subtree of node to an absolute depth of 5\n  node.descendants(:at_depth =\u003e 2)  Descendant of node, at depth node.depth + 2 (grandchildren)\n  node.descendants.at_depth(10)     Descendants of node at an absolute depth of 10\n  node.ancestors.to_depth(3)        The oldest 4 ancestors of node (its root and 3 more)\n  node.path(:from_depth =\u003e -2)      The node's grandparent, parent and the node itself\n\n  node.ancestors(:from_depth =\u003e -6, :to_depth =\u003e -4)\n  node.path.from_depth(3).to_depth(4)\n  node.descendants(:from_depth =\u003e 2, :to_depth =\u003e 4)\n  node.subtree.from_depth(10).to_depth(12)\n\nPlease note that depth constraints cannot be passed to ancestor_ids and path_ids. The reason for this is that both these relations can be fetched directly from the ancestry column without performing a database query. It would require an entirely different method of applying the depth constraints which isn't worth the effort of implementing. You can use ancestors(depth_options).map(\u0026:id) or ancestor_ids.slice(min_depth..max_depth) instead.\n\n= STI support\n\nAncestry works fine with STI. Just create a STI inheritance hierarchy and build an Ancestry tree from the different classes/models. All Ancestry relations that where described above will return nodes of any model type. If you do only want nodes of a specific subclass you'll have to add a condition on type for that.\n\n= Arrangement\n\nAncestry can arrange an entire subtree into nested hashes for easy navigation after retrieval from the database.  TreeNode.arrange could for example return:\n\n  { #\u003cTreeNode id: 100018, name: \"Stinky\", ancestry: nil\u003e\n    =\u003e { #\u003cTreeNode id: 100019, name: \"Crunchy\", ancestry: \"100018\"\u003e\n      =\u003e { #\u003cTreeNode id: 100020, name: \"Squeeky\", ancestry: \"100018/100019\"\u003e\n        =\u003e {}\n      }\n    }\n  }\n\nThe arrange method also works on a scoped class, for example:\n\n  TreeNode.find_by_name('Crunchy').subtree.arrange\n\nThe arrange method takes ActiveRecord find options. If you want your hashes to be ordered, you should pass the order to the arrange method instead of to the scope. This also works for Ruby 1.8 since an OrderedHash is returned. For example:\n\n  TreeNode.find_by_name('Crunchy').subtree.arrange(:order =\u003e :name)\n\nTo get the arranged nodes as a nested array of hashes for serialization:\n\n  TreeNode.arrange_serializable\n\n  [\n    {\n      \"ancestry\" =\u003e nil, \"id\" =\u003e 1, \"children\" =\u003e [\n        { \"ancestry\" =\u003e \"1\", \"id\" =\u003e 2, \"children\" =\u003e [] }\n      ]\n    }\n  ]\n\nThe result of arrange_serializable can easily be serialized to json with 'to_json', or some other format:\n\n  TreeNode.arrange_serializable.to_json\n\nYou can also pass the order to the arrange_serializable method just as you can pass it to the arrange method:\n\n  TreeNode.arrange_serializable(:order =\u003e :name)\n\n= Sorting\n\nIf you just want to sort an array of nodes as if you were traversing them in preorder, you can use the sort_by_ancestry class method:\n\n  TreeNode.sort_by_ancestry(array_of_nodes)\n\nNote that since materialised path trees don't support ordering within a rank, the order of siblings depends on their order in the original array.\n\n= Migrating from plugin that uses parent_id column\n\nMost current tree plugins use a parent_id column (has_ancestry, awesome_nested_set, better_nested_set, acts_as_nested_set). With ancestry its easy to migrate from any of these plugins, to do so, use the build_ancestry_from_parent_ids! method on your ancestry model. These steps provide a more detailed explanation:\n\n1. Add ancestry column to your table\n   - Create migration: \u003cb\u003erails g migration add_ancestry_to_[table] ancestry:string\u003c/b\u003e\n   - Add index to migration: \u003cb\u003eadd_index [table], :ancestry\u003c/b\u003e (UP) / \u003cb\u003eremove_index [table], :ancestry\u003c/b\u003e (DOWN)\n   - Migrate your database: \u003cb\u003erake db:migrate\u003c/b\u003e\n\n2. Remove old tree plugin or gem and add in Ancestry\n   - Remove plugin: rm -Rf vendor/plugins/[old plugin]\n   - Remove gem config line from environment.rb: config.gem [old gem]\n   - Add Ancestry to environment.rb: config.gem :ancestry\n   - See 'Installation' for more info on installing and configuring gems\n\n3. Change your model\n   - Remove any macros required by old plugin/gem from app/models/[model].rb\n   - Add to app/models/[model].rb: \u003cb\u003ehas_ancestry\u003c/b\u003e\n\n4. Generate ancestry columns\n   - In './script.console': \u003cb\u003e[model].build_ancestry_from_parent_ids!\u003c/b\u003e\n   - Make sure it worked ok: \u003cb\u003e[model].check_ancestry_integrity!\u003c/b\u003e\n\n5. Change your code\n   - Most tree calls will probably work fine with ancestry\n   - Others must be changed or proxied\n   - Check if all your data is intact and all tests pass\n\n6. Drop parent_id column:\n   - Create migration: \u003cb\u003erails g migration remove_parent_id_from_[table]\u003c/b\u003e\n   - Add to migration: \u003cb\u003eremove_column [table], :parent_id\u003c/b\u003e (UP) / \u003cb\u003eadd_column [table], :parent_id, :integer\u003c/b\u003e (DOWN)\n   - Migrate your database: \u003cb\u003erake db:migrate\u003c/b\u003e\n\n= Integrity checking and restoration\n\nI don't see any way Ancestry tree integrity could get compromised without explicitly setting cyclic parents or invalid ancestry and circumventing validation with update_attribute, if you do, please let me know.\n\nAncestry includes some methods for detecting integrity problems and restoring integrity just to be sure. To check integrity use: [Model].check_ancestry_integrity!. An AncestryIntegrityException will be raised if there are any problems. You can also specify :report =\u003e :list to return an array of exceptions or :report =\u003e :echo to echo any error messages. To restore integrity use: [Model].restore_ancestry_integrity!.\n\nFor example, from IRB:\n\n  \u003e\u003e stinky = TreeNode.create :name =\u003e 'Stinky'\n  $  #\u003cTreeNode id: 1, name: \"Stinky\", ancestry: nil\u003e\n  \u003e\u003e squeeky = TreeNode.create :name =\u003e 'Squeeky', :parent =\u003e stinky\n  $  #\u003cTreeNode id: 2, name: \"Squeeky\", ancestry: \"1\"\u003e\n  \u003e\u003e stinky.update_attribute :parent, squeeky\n  $  true\n  \u003e\u003e TreeNode.all\n  $  [#\u003cTreeNode id: 1, name: \"Stinky\", ancestry: \"1/2\"\u003e, #\u003cTreeNode id: 2, name: \"Squeeky\", ancestry: \"1/2/1\"\u003e]\n  \u003e\u003e TreeNode.check_ancestry_integrity!\n  !! Ancestry::AncestryIntegrityException: Conflicting parent id in node 1: 2 for node 1, expecting nil\n  \u003e\u003e TreeNode.restore_ancestry_integrity!\n  $  [#\u003cTreeNode id: 1, name: \"Stinky\", ancestry: 2\u003e, #\u003cTreeNode id: 2, name: \"Squeeky\", ancestry: nil\u003e]\n\nAdditionally, if you think something is wrong with your depth cache:\n\n  \u003e\u003e TreeNode.rebuild_depth_cache!\n\n= Tests\n\nThe Ancestry gem comes with a unit test suite consisting of about 1900 assertions in about 50 tests. It takes about 10 seconds to run on sqlite. It is run against three databases (sqlite3, mysql and postgresql) and four versions of Activerecord (3.0, 3.1, 3.2 and 4.0) using Appraisals. To run it yourself:\n- Check out the repository from GitHub\n- Copy test/database.example.yml to test/database.yml\n- Run \u003ctt\u003ebundle\u003c/tt\u003e\n- Run \u003ctt\u003eappraisal install\u003c/tt\u003e\n- Run \u003ctt\u003eappraisal rake test\u003c/tt\u003e\n\nYou can also run against a specific database and specific version of Activerecord:\n- Run the above commands, except for the last one\n- Run \u003ctt\u003eappraisal sqlite3-ar-32 rake test\u003c/tt\u003e (to test against sqlite3 and Activerecord 3.2)\n\n= Internals\n\nAs can be seen in the previous section, Ancestry stores a path from the root to the parent for every node. This is a variation on the materialised path database pattern. It allows Ancestry to fetch any relation (siblings, descendants, etc.) in a single SQL query without the complicated algorithms and incomprehensibility associated with left and right values. Additionally, any inserts, deletes and updates only affect nodes within the affected node's own subtree.\n\nIn the example above, the ancestry column is created as a string. This puts a limitation on the depth of the tree of about 40 or 50 levels, which I think may be enough for most users. To increase the maximum depth of the tree, increase the size of the string that is being used or change it to a text to remove the limitation entirely. Changing it to a text will however decrease performance because an index cannot be put on the column in that case.\n\nThe materialised path pattern requires Ancestry to use a 'like' condition in order to fetch descendants. This should not be particularly slow however since the the condition never starts with a wildcard which allows the DBMS to use the column index. If you have any data on performance with a large number of records, please drop me line.\n\n= Contributing and licence\n\nI will try to keep Ancestry up to date with changing versions of Rails and Ruby and also with any bug reports I might receive. I will implement new features on request as I see fit and have time.\n\nQuestion? Bug report? Faulty/incomplete documentation? Feature request? Please post an issue on 'http://github.com/stefankroes/ancestry/issues'. Make sure you have read the documentation and you have included tests and documentation with any pull request.\n\nCopyright (c) 2013 Stefan Kroes, released under the MIT license\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmediafellows%2Fancestry","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmediafellows%2Fancestry","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmediafellows%2Fancestry/lists"}