Acts_as_nested_set first record foreign key error

I’m trying to use nested set. When I try to insert the first row with a
parent_id of 0 I get an error because of the foreign key constraint on
parent_id failing.

Obviously the parent_id can’t be 0 if there is no row with an id of 0,
but nested_set REQUIRES that the parent_id of a root be 0. So, I thought
maybe (since the documentation is lacking) that I don’t need the
constraint on parent_id, so I removed it and it did not work at all when
I inserted child objects. So, how do I get the first row inserted with a
parent_id of 0?

Thanks.

Man, this is confusing…

I can make things work (sort of) by doing the following:

  1. I keep the constraint on parent_id and set the root parent_id to null
    instead of 0. (Just like with acts_as_tree)

  2. I create the first record (from the console) which is the root:
    root = Model.create(“attributes” => “attributes”)

  3. Then I create the second record:
    child1 = Model.create(“attributes” => “attributes”)

  4. Then I set child1 as a child of the root:
    root.add_child(child1)

  5. Then I check the database and the lft and rgt values are not
    correct. They show as:

    id parent_id lft rgt
    1 NULL 0 2
    2 1 0 1

  6. Obviously this is not correct, so I manually change the values in the
    database to the following:

    id parent_id lft rgt
    1 NULL 1 4
    2 1 2 3

  7. Then I add all the children, grand children etc…

    subchild1 = Model.create(“attributes” => “attributes”)
    child1.add_child(subchild1)
    child2 = Model.create(“attributes” => “attributes”)
    root.add_child(child2)
    subchild2 = Model.create(“attributes” => “attributes”)
    child2.add_child(subchild2)
    etc…

All of the other children and grand children are created successfully
and the lft and rgt values are updated accordingly and correctly.

So, the question remains…why can’t I create the first records
correctly? Also, how do I create additional roots and their children
without manually updating the lft and rgt values?

(Sorry about the tags, they work in a different forum where I’m
asking the question and I copy/pasted from there…my bad.)