Bird
Raised Fist0
Ruby on Railsframework~10 mins

Numericality validation in Ruby on Rails - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Numericality validation
Start: Model with attribute
↓
Apply numericality validation
↓
Input value assigned
↓
Check if value is a number
↓
Pass
↓
Save success
↓
End
This flow shows how Rails checks if a model attribute is a number during validation, allowing save if valid or adding errors if not.
Execution Sample
Ruby on Rails
class Product < ApplicationRecord
  validates :price, numericality: true
end

product = Product.new(price: 'abc')
product.valid?
This code checks if the price attribute is a number; here it tests with a non-numeric string.
Execution Table
StepActionInput ValueValidation CheckResultError Added
1Assign price'abc'N/AValue setNo
2Run numericality validation'abc'Is 'abc' a number?NoYes: 'price is not a number'
3Check product validityN/AAre there errors?YesYes
4Attempt saveN/AValid? FalseSave failsYes
💡 Validation fails because 'abc' is not a number, so save is prevented.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
product.pricenil'abc''abc''abc''abc'
product.errors[:price][][]['is not a number']['is not a number']['is not a number']
product.valid?nilnilfalsefalsefalse
Key Moments - 3 Insights
Why does the validation fail when price is 'abc'?
Because 'abc' is not a number, the numericality check returns false and adds an error (see execution_table step 2).
What happens if price is a number like 10?
The validation passes, no errors are added, and the product can be saved successfully (not shown here but implied).
Does numericality validation allow strings that look like numbers?
Yes, strings like '10' are valid numbers and pass validation, but non-numeric strings like 'abc' fail.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what error message is added when price is 'abc'?
A'price must be greater than zero'
B'price can't be blank'
C'price is not a number'
DNo error message
💡 Hint
Check the 'Error Added' column in step 2 of the execution_table.
At which step does the product become invalid due to numericality validation?
AStep 2
BStep 3
CStep 1
DStep 4
💡 Hint
Look at the 'Validation Check' and 'Result' columns in the execution_table.
If price was set to 25 instead of 'abc', how would the 'product.valid?' value change after step 3?
AIt would be false
BIt would be true
CIt would be nil
DIt would cause an error
💡 Hint
Refer to variable_tracker for 'product.valid?' and consider a valid numeric input.
Concept Snapshot
Numericality validation in Rails checks if an attribute is a number.
Use: validates :attribute, numericality: true
If the value is not numeric, validation fails and errors are added.
Valid numeric strings like '10' pass; non-numeric like 'abc' fail.
This prevents saving invalid data to the database.
Full Transcript
Numericality validation in Rails ensures a model attribute holds a number. When you assign a value to the attribute, Rails checks if it is numeric during validation. If the value is not a number, Rails adds an error message like 'is not a number' and prevents saving the record. For example, if you set price to 'abc', validation fails. But if you set price to 10 or '10', validation passes. This helps keep data clean and correct in your app.

Practice

(1/5)
1. What does the validates :age, numericality: true line do in a Rails model?
easy
A. It checks if age is a string.
B. It makes the age attribute required.
C. It ensures the age attribute is a number.
D. It sets a default value for age.

Solution

  1. Step 1: Understand numericality validation

    The numericality: true option checks if the attribute is a number.
  2. Step 2: Apply to age attribute

    Since it is applied to age, it ensures age must be numeric.
  3. Final Answer:

    It ensures the age attribute is a number. -> Option C
  4. Quick Check:

    Numericality validation = ensures number [OK]
Hint: Numericality means the value must be a number [OK]
Common Mistakes:
  • Confusing numericality with presence validation
  • Thinking it sets default values
  • Assuming it checks for strings
2. Which of the following is the correct syntax to validate that price is an integer in Rails?
easy
A. validates :price, numericality: { only_integer: true }
B. validates :price, integer: true
C. validates :price, number: { integer: true }
D. validates :price, numericality: true, integer: true

Solution

  1. Step 1: Recall correct numericality syntax

    Rails uses numericality: { only_integer: true } to check integers.
  2. Step 2: Check options

    validates :price, numericality: { only_integer: true } matches this syntax exactly; others are invalid or incorrect.
  3. Final Answer:

    validates :price, numericality: { only_integer: true } -> Option A
  4. Quick Check:

    Integer validation uses only_integer: true [OK]
Hint: Use only_integer inside numericality hash [OK]
Common Mistakes:
  • Using a separate integer key instead of inside numericality
  • Writing invalid keys like number or integer alone
  • Missing curly braces for options
3. Given this model validation:
validates :score, numericality: { greater_than: 0, less_than_or_equal_to: 100 }

What happens if you try to save score = 150?
medium
A. Validation fails because 150 is greater than 100.
B. The record saves successfully.
C. Validation fails because 150 is less than 0.
D. Validation passes because 150 is a number.

Solution

  1. Step 1: Understand validation limits

    The validation requires score to be greater than 0 and less than or equal to 100.
  2. Step 2: Check the value 150

    150 is greater than 100, so it violates the less_than_or_equal_to: 100 rule.
  3. Final Answer:

    Validation fails because 150 is greater than 100. -> Option A
  4. Quick Check:

    Value must be ≤ 100, 150 fails [OK]
Hint: Check all numerical limits carefully [OK]
Common Mistakes:
  • Ignoring upper limit and assuming number is valid
  • Confusing greater_than with greater_than_or_equal_to
  • Assuming any number passes
4. Identify the error in this validation:
validates :quantity, numericality: { only_integer: true, greater_than: 0, less_than: 10, message: 'must be a number' }
medium
A. There is no error; this validation is correct.
B. The message option is misplaced inside the numericality hash.
C. The validation is missing presence: true.
D. The only_integer option cannot be combined with greater_than.

Solution

  1. Step 1: Check placement of message

    The message option should be outside the numericality options hash, not inside it.
  2. Step 2: Validate other options

    only_integer, greater_than, and less_than can be combined correctly.
  3. Final Answer:

    The message option is misplaced inside the numericality hash. -> Option B
  4. Quick Check:

    Message option goes outside numericality hash [OK]
Hint: Put message outside numericality options hash [OK]
Common Mistakes:
  • Placing message inside numericality hash
  • Thinking only_integer conflicts with other options
  • Assuming presence is required for numericality
5. You want to validate a rating attribute that must be an integer between 1 and 5 inclusive. Which validation code correctly enforces this?
hard
A. validates :rating, numericality: { only_integer: true, greater_than: 1, less_than: 5 }
B. validates :rating, numericality: { only_integer: true, greater_than: 1, less_than_or_equal_to: 5 }
C. validates :rating, numericality: { only_integer: true, greater_than_or_equal_to: 1, less_than: 5 }
D. validates :rating, numericality: { only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 5 }

Solution

  1. Step 1: Understand inclusive range requirements

    The rating must include 1 and 5, so use greater_than_or_equal_to: 1 and less_than_or_equal_to: 5.
  2. Step 2: Check integer enforcement

    only_integer: true ensures rating is an integer.
  3. Step 3: Compare options

    validates :rating, numericality: { only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 5 } matches all requirements exactly; others exclude 1 or 5 or use wrong operators.
  4. Final Answer:

    validates :rating, numericality: { only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 5 } -> Option D
  5. Quick Check:

    Inclusive integer range uses >= and <= [OK]
Hint: Use greater_than_or_equal_to and less_than_or_equal_to for inclusive range [OK]
Common Mistakes:
  • Using greater_than or less_than excludes boundary values
  • Forgetting only_integer for integer check
  • Mixing up operators for inclusive range
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard