Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Self-referential model breaks #ancestors method. #397

Closed
rockwellll opened this issue Apr 22, 2022 · 1 comment
Closed

Self-referential model breaks #ancestors method. #397

rockwellll opened this issue Apr 22, 2022 · 1 comment

Comments

@rockwellll
Copy link

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

@seuros
Copy link
Member

seuros commented Jul 31, 2022

It something related to your code. I could not reproduce it. If you provide a demo repo, i can look at it.

@seuros seuros closed this as completed Jul 31, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants