Challenge - 5 Problems
Numericality Validation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2:00remaining
What happens when a model with numericality validation receives a non-numeric value?
Consider a Rails model with
validates :age, numericality: true. What will be the validation result if age is set to 'twenty'?Ruby on Rails
class User < ApplicationRecord validates :age, numericality: true end user = User.new(age: 'twenty') user.valid? user.errors.full_messages
Attempts:
2 left
💡 Hint
Think about what numericality validation expects as input.
✗ Incorrect
The numericality validation checks if the attribute is a valid number. A string like 'twenty' is not numeric, so validation fails with an error message.
📝 Syntax
intermediate2:00remaining
Which validation syntax correctly enforces an integer value only?
You want to validate that the attribute
quantity is an integer number only. Which of the following validation lines is correct?Attempts:
2 left
💡 Hint
Check the correct option key inside the numericality hash.
✗ Incorrect
The correct option is only_integer: true inside the numericality hash. Other options are either misplaced or incorrect keys.
❓ state_output
advanced2:00remaining
What is the error message when a number is less than the minimum allowed?
Given the validation
validates :score, numericality: { greater_than_or_equal_to: 10 }, what error message appears if score is set to 5?Ruby on Rails
class Game < ApplicationRecord validates :score, numericality: { greater_than_or_equal_to: 10 } end game = Game.new(score: 5) game.valid? game.errors.full_messages
Attempts:
2 left
💡 Hint
Look carefully at the validation option used.
✗ Incorrect
The validation uses greater_than_or_equal_to: 10, so the error message reflects that the score must be at least 10.
🔧 Debug
advanced2:00remaining
Why does this numericality validation not work as expected?
This model validation is intended to allow only positive integers, but it accepts negative numbers. Why?
validates :count, numericality: { only_integer: true, greater_than: 0 }Ruby on Rails
class Item < ApplicationRecord validates :count, numericality: { only_integer: true, greater_than: 0 } end item = Item.new(count: -3) item.valid? item.errors.full_messages
Attempts:
2 left
💡 Hint
Try running the code and check the errors.
✗ Incorrect
The validation correctly rejects negative numbers because of greater_than: 0. Negative values cause validation to fail.
🧠 Conceptual
expert2:00remaining
How does the
allow_nil option affect numericality validation?Consider
validates :price, numericality: true, allow_nil: true. What is the behavior when price is nil?Attempts:
2 left
💡 Hint
Think about what allow_nil means for validations.
✗ Incorrect
The allow_nil: true option skips numericality validation if the attribute is nil, so validation passes without errors.