rocLv
rocLv

Reputation: 568

Ruby On Rails: Figure out two or more records fields value overlap?

I have a table with two fields, range_from and range_to. Both fields are integer. If one record's range_from is less than last record's range_to, then get false, otherwise, get true.

For example:

+----+------------+----------+
| id | range_from | range_to |
+----+------------+----------+
| 1  | 4          | 10       |
| 2  | 6          | 12       |
+----+------------+----------+

Because 6 < 10, so I should get false.

I found a gem named "validate-overlaps", but it looks like to deal with DateTime overlap.

It's ok validate this from model or controller.

Upvotes: 0

Views: 97

Answers (1)

sebkkom
sebkkom

Reputation: 1446

As shivam suggested, you can write a method. Something like:

def validate_range
  self.errors.add(:range_from, "is less than the last range_to") unless (self.range_from > Model.last.range_to)
end

Upvotes: 1

Related Questions