Marko Krstic
Marko Krstic

Reputation: 1447

rails 4: ancestry doesn't work properly?

I have a problem when try to do root_id of one object. Class looks like:

# == Schema Information
#
#  id         :integer          not null, primary key
#  name       :string(255)
#  ancestry   :string(255)

class PackageCategory < ActiveRecord::Base
    has_ancestry
end

that database table looks:

id   name         ancestry
1    Root         NULL
2    Child 1-1    1
3    Child 1-2    1
4    Child 2-1    2
5    Child 3-1    4

When I do:

@p = PackageCategory.find 5
puts @p.root_id

I am getting: 4

When I type:

@p.path_ids

I am getting: [4, 5]

puts @p.name gives me Child 3-1 (and it's correct)

So, where is a problem? Shouldn't I get in the first case 1 and in the second [1, 2, 4, 5] ?

Upvotes: 1

Views: 565

Answers (1)

Alejandro Babio
Alejandro Babio

Reputation: 5229

At this point, I can say that ancestry column is not well formated. Because, if I look the record with id 4 (Child 2-1) its ancestry says his parent is the record id 2, and the record 2 is a root record. And that is false.

The format at ancestry column is 'root_id/son_id/son_id/.../parent_of_current_record_id'.

The ancestry column of record id 4 must be set with:

pc = PackageCategory.find(4)
pc.parent = PackageCategory.find(2)
pc.save

or

pc.parent_id = 2
pc.save

And the ancestry gem build the ancestry column.

Upvotes: 1

Related Questions