The only_numeric
validation, introduced in Rails 7, empowers developers to enforce stricter constraints on model attributes. This ensures that only numeric values are accepted, improving data integrity in various scenarios. Imagine collecting phone numbers or product quantities – only_numeric
guarantees user input adheres to the expected format.
Using the only_numeric
Validation
Here’s how to implement only_numeric
validation in a Rails model:
1
2
3
class Product < ApplicationRecord
validates_numericality_of :quantity, only_numeric: true
end
This example uses the validates_numericality_of
method with the only_numeric: true
option. This ensures the quantity
attribute contains only numbers. Any attempt to create a product with a non-numeric value in quantity
will trigger validation failure, preventing the record from being saved.
Important Notes:
- Nil by Default: The
numericality
validation does not allownil
values by default. - Allowing Nil: If you want to allow the attribute to be null, you can use the
allow_nil: true
option:
1
2
3
class Product < ApplicationRecord
validates_numericality_of :quantity, only_numeric: true, allow_nil: true
end
With this configuration, the validation will allow both numeric values and nil
.
Invalid Input
1
2
Product.create!(quantity: "10 units")
=> raises ActiveRecord::RecordInvalid with message: "Quantity is not a number"
As expected, creating a product with a string value (“10 units”) for quantity
fails validation. The only_numeric
option ensures the value is a number, not a combination of digits and text.
Valid Input
1
2
Product.create!(quantity: 10)
=> #<Product id: 2, quantity: 10, created_at: ..., updated_at: ...>
Creating a product with a numeric value for quantity
successfully passes validation. The record is saved and the quantity
is stored as an integer in the database.