Skip to content

Self-referential model breaks #ancestors method. #397

Closed
@rockwellll

Description

@rockwellll

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

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