Skip to content

How to add parent_id to existing instances? #494

Description

@paddy-hack

I followed the Installation instructions from the README.md but was confused by the last step. That says

  1. If you're migrating from another system where your model already has a parent_id column, run Tag.rebuild! and your tag_hierarchies table will be truncated and rebuilt.

If you're starting from scratch you don't need to call rebuild!.

At this point, my model has a parent_id column but I am not migrating from another system. I am simply adding hierarchy to an existing model, let's call it Tag, and the database has a small pile of instances. The migrations added the parent_id column to that model and closure_tree:migration generator added an empty tag_hierarchies table to the database. All Tag instances have their parent_id attribute set to nil at this point.

If I then execute something like Tag.first.ancestry_path in the Rails console, I get an empty array. I had expected to get an array with Tag.first.name.

Running Tag.rebuild! (before saving any parent_id values to the database) seems to fix this but I am not sure if that is what I am supposed to be doing given the documentation. If it is, is doing this backfilling in a migration the recommended way of doing so? How would I revert that?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions