0
0
Ruby on Railsframework~20 mins

Length validation in Ruby on Rails - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Length Validation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
How does this length validation behave?
Consider this Rails model validation:

validates :username, length: { minimum: 3, maximum: 8 }

What happens if you try to save a user with username 'Jo'?
AThe save fails because 'Jo' is longer than the maximum length 8.
BThe save succeeds because 'Jo' is a valid string.
CThe save succeeds but triggers a warning.
DThe save fails because 'Jo' is shorter than the minimum length 3.
Attempts:
2 left
💡 Hint
Think about what minimum length means for a string.
📝 Syntax
intermediate
2:00remaining
Which length validation syntax is correct?
Which of these is the correct way to validate that a Rails model's attribute 'title' has a length exactly 5 characters?
Avalidates :title, length: { min: 5, max: 5 }
Bvalidates_length_of :title, equal_to: 5
Cvalidates :title, length: { is: 5 }
Dvalidates :title, length: 5
Attempts:
2 left
💡 Hint
Look for the official Rails length validation option for exact length.
state_output
advanced
2:00remaining
What error message appears for this validation?
Given this validation:

validates :password, length: { minimum: 6, too_short: 'must have at least %{count} characters' }

What error message will appear if password is '123'?
A"Password is invalid"
B"must have at least 6 characters"
C"Password is too short (minimum is 6 characters)"
D"Password must be at least 3 characters"
Attempts:
2 left
💡 Hint
The custom message uses %{count} to show the minimum length.
🔧 Debug
advanced
2:00remaining
Why does this length validation not work as expected?
Look at this validation:

validates :code, length: { minimum: 4, maximum: 10, message: 'length must be between 4 and 10' }

Why might the error message not show when the code is too short or too long?
AThe :message option applies to all length errors, but Rails expects separate messages for minimum and maximum.
BThe :message option is ignored because it must be outside the length hash.
CThe validation syntax is invalid and causes a syntax error.
DThe attribute :code is missing from the model.
Attempts:
2 left
💡 Hint
Check how Rails handles error messages for length validations.
🧠 Conceptual
expert
2:00remaining
How does length validation interact with nil values?
Given this validation:

validates :nickname, length: { maximum: 10 }

If the nickname is nil, what happens when saving the model?
AThe validation passes because length validation ignores nil values by default.
BThe validation fails because nil has no length.
CThe validation raises a runtime error.
DThe validation passes only if :allow_nil is set to true.
Attempts:
2 left
💡 Hint
Think about how Rails treats nil values in length validations by default.