Skip to content

Commit

Permalink
Merge branch 'alistairm/numericality-range'
Browse files Browse the repository at this point in the history
  • Loading branch information
amckinnell committed Jun 21, 2024
2 parents 98b04cb + b946d8c commit 65a4200
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions _posts/2024-06-19-Numericality-Range.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
---
layout: post
title: "Using a Range in a Numericality Validation"
author: alistairmckinnell
date: 2024-06-19T23:16:00
excerpt: "Rails 7.0 allows a more compact way to specify allowed values in a numericality validation."
---

Rails `7.0` allows a more compact way to specify allowed values in a numericality validation.

Instead of using combinations of `greater_than`, `greater_than_or_equal_to`, `less_than`, and `less_than_or_equal_to`,
you can use `in` with a range.

**Before**

```Ruby
validates :setting_reuse, numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 12 }
```

**After**

```Ruby
validates :setting_reuse, numericality: { in: 0..12 }
```

You get all the expressiveness that a range provides.
Here are more examples each showing before and after:

```Ruby
validates :setting_reuse, numericality: { greater_than_or_equal_to: 2 }
validates :setting_reuse, numericality: { in: 2... }
```

```Ruby
validates :setting_reuse, numericality: { less_than: 12 }
validates :setting_reuse, numericality: { in: ...12 }
```

0 comments on commit 65a4200

Please sign in to comment.