Hello. Hoping you're having a good day. So, i've a setup that looks like this
class Step
has_closure_tree
belongs_to :root_step, class_name: "Step", foreign_key: :root_step_id, optional: true
has_many :versions, class_name: "Step", foreign_key: :root_step_id
end
We have a requirement that states A step must either belong to a root step. or root step is itself. According to that, what i'm doing is
after_create do
update root_step_id: self.id unless root_step_id.present?
end
I am setting the root_step_id of a step to itself.
When doing so. It breaks the ancestry method. It always return nil. However, i can call #parent method, i.e ste.parent.parent and all works fine. But if i want to access the step's ancestors it will always return me nil.
3.1.0 :006 > step2.parent
=>
#<Step:0x000000010c8d5f38
id: 306,
parent_id: nil,
root_step_id: 306>
However, doing step2.parent will always return me nil.
3.1.0 :007 > step2.ancestors
Step Load (0.7ms) SELECT "steps".* FROM "steps" INNER JOIN "step_hierarchies" ON "steps"."id" = "step_hierarchies"."ancestor_id" WHERE "step_hierarchies"."descendant_id" = $1 AND ("steps"."id" != 307) ORDER BY "step_hierarchies".generations ASC [["descendant_id", 307]]
=> []
Why calling #ancestors returns nil?. I think for some reason the self-referential reference to itself is causing that. Because when i removed it everything works fine.
Thanks
Hello. Hoping you're having a good day. So, i've a setup that looks like this
We have a requirement that states A step must either belong to a root step. or root step is itself. According to that, what i'm doing is
I am setting the
root_step_idof a step to itself.When doing so. It breaks the ancestry method. It always return nil. However, i can call
#parentmethod, i.este.parent.parentand all works fine. But if i want to access the step's ancestors it will always return me nil.However, doing
step2.parentwill always return me nil.Why calling
#ancestorsreturns nil?. I think for some reason the self-referential reference to itself is causing that. Because when i removed it everything works fine.Thanks