Home > Enterprise >  How do I check for validation for redirection to void cyclic redirection loop in ruby on rails?
How do I check for validation for redirection to void cyclic redirection loop in ruby on rails?

Time:10-23

I have a redirection model with two columns to and from. I also have a frontend UI, where the redirections can be added.

I need to know whether is there any solution to avoid cyclic redirect loop by creating a before_save validation or some thing else.

Some of the redirection test cases:

Cyclic redirection (will cause a redirection loop)

1 -> 2
2 -> 3
3 -> 4

4 -> 1

Chained redirection (will not cause a redirection loop)

1 -> 2
2 -> 3

4 -> 1

Cyclic redirection (will cause redirection loop)

1 -> 1

CodePudding user response:

If I understand well, basically you don't want that the columns to and from be the same. It is very easy to do such a thing. In your redirection model, you can add :

class Redirection < ApplicationRecord
...

validate :to_and_from_not_equal

private

def to_and_from_not_equal
  if self.to == self.from
    errors.add(:base, "To and From cannot be equal")
  end
end

Then you cannot create your Redirection record if both values are equal.

CodePudding user response:

class Redirection < ApplicationRecord
...

validate :to_and_from_not_equal
validate :check_redirection_loop

private

def to_and_from_not_equal
  if self.to == self.from
    errors.add(:base, "To and From cannot be equal")
  end
end

def check_redirection_loop
  if to_exist_in_from? && from_exist_in_to?
    errors.add(:base, "This redirection causes redirection loop")
  end
end

def to_exist_in_from?
  Redirection.where(to: self.from).present?
end

def from_exist_in_to?
  Redirection.where(from: self.to).present?
end

This is the answer extending @Maxence's answer. This works for me now. There can be improvements in the codebase.

  • Related