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

Defining a maximal depth #540

Open
edouard-per-angusta opened this issue Apr 29, 2021 · 1 comment
Open

Defining a maximal depth #540

edouard-per-angusta opened this issue Apr 29, 2021 · 1 comment

Comments

@edouard-per-angusta
Copy link

edouard-per-angusta commented Apr 29, 2021

Hi! I try to validate a maximal depth, but it seems that Rails validations are skipped when cached depth is updated after a parent has been updated.

For example, given I want this maximal depth to be 1:

Node.has_ancestry(cache_depth: true)
Node.validates(:ancestry_depth, numericality: { less_than_or_equal_to: 1 })

a = Node.create!            # ancestry_depth == 0
b = Node.create!(parent: a) # ancestry_depth == 1
c = Node.create!(parent: b) # error, as expected

x = Node.create!            # ancestry_depth == 0
a.update!(parent: x)        # it works, but then b.ancestry_depth == 2, which is not allowed

For now I've added a validation on update like:

def validate_descendants_ancestry_depth
  return unless ancestry_changed?
  return if descendants.maximum(:ancestry_depth) + ancestry_depth - ancestry_depth_was <= 1

  errors.add(...)
end

But I was wondering if there was a built-in system for that? Like something checking if there is any other ActiveModel::Validations::NumericalityValidator on the ancestry_depth attribute?

Thanks! :)

@kbrock
Copy link
Collaborator

kbrock commented May 24, 2021

wonderful edge case.

there is no way to determine that you have kids (without a query)
I guess there is a way to know that you are a new node - so we could skip the check in that instance

Could also only add this validation in has_ancestry when the depth validation is added.

This just feels like an expensive check.

Curious, are you running this on postgres or mysql? Probably doesn't make a difference, but we approach them slightly differently.

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