---
title: "Rails 7 adds only_numeric option to numericality validator"
description: "Rails 7 adds only_numeric option to numericality validator"
canonical_url: "https://www.bigbinary.com/blog/rails-7-adds-only_numeric-option-to-numericality-validator"
markdown_url: "https://www.bigbinary.com/blog/rails-7-adds-only_numeric-option-to-numericality-validator.md"
---

# Rails 7 adds only_numeric option to numericality validator

Rails 7 adds only_numeric option to numericality validator

- Author: Aditya Bhutani
- Published: January 17, 2022
- Categories: Rails, Rails 7

Rails 7.0.1 introduces `only_numeric` option to the numericality validator which
specifies whether the value has to be an instance of Numeric. The default
behavior is to attempt parsing the value if it is a String.

When the database field is a float column, the data will get serialized to the
correct type. In the case of a JSON column, serialization doesn't take place.

As a resolution, Rails 7 has added `only_numeric` option to numericality
validator.

We will see it in action.

To demonstrate, we need to generate a table that has a json/jsonb column.

```ruby
# migration
create_table :users do |t|
  t.jsonb :personal
end
```

### Before Validation

```ruby
# Model
class User < ApplicationRecord
  store_accessor :personal, %i[age tooltips]
end
```

```ruby
# rails console
>> User.create!(age: '29')
=> #<User id: 1, preferences: {"age"=>"29"}, created_at: Sun, 16 Jan 2022 14:09:43.045301000 UTC +00:00, updated_at: Sun, 16 Jan 2022 14:09:43.045301000 UTC +00:00>
```

### After Validation

```ruby
# Model
class User < ApplicationRecord
  store_accessor :personal, %i[age tooltips]
  validates_numericality_of :age, only_numeric: true, allow_nil: true
end
```

```ruby
# rails console
>> User.create!(age: '29')
=> 'raise_validation_error': Validation failed: Age is not a number (ActiveRecord::RecordInvalid)

>> User.create!(age: 29)
=> #<User id: 2, preferences: {"age"=>29}, created_at: Sun, 16 Jan 2022 14:15:44.599934000 UTC +00:00, updated_at: Sun, 16 Jan 2022 14:15:44.599934000 UTC +00:00>
```

Please check out this [pull request](https://github.com/rails/rails/pull/43914)
for more details.

## Links

- [Human page](https://www.bigbinary.com/blog/rails-7-adds-only_numeric-option-to-numericality-validator)
