Concept Flow - Length validation
Start: Model with attribute
Add length validation rule
Save or update record
Check attribute length
Save OK
End
Rails checks the attribute length when saving a record. If valid, it saves; if not, it adds an error.
class User < ApplicationRecord validates :username, length: { minimum: 3, maximum: 10 } end
| Step | Attribute Value | Length Check | Result | Action |
|---|---|---|---|---|
| 1 | "Jo" | Length = 2 | Too short (min 3) | Add error, do not save |
| 2 | "John" | Length = 4 | Valid | Save record |
| 3 | "AlexanderTheGreat" | Length = 17 | Too long (max 10) | Add error, do not save |
| 4 | "Alice123" | Length = 8 | Valid | Save record |
| Attribute Value | Start | After 1 | After 2 | After 3 | After 4 |
|---|---|---|---|---|---|
| username | nil | "Jo" | "John" | "AlexanderTheGreat" | "Alice123" |
Rails length validation checks attribute length on save.
Syntax: validates :attr, length: { minimum: x, maximum: y }
If length is outside range, record is not saved and errors added.
Runs automatically during save or update.
Use to ensure data fits expected size limits.