Bird
Raised Fist0
Ruby on Railsframework~10 mins

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

Choose your learning style10 modes available
Concept Flow - Presence validation
Start: Create model instance
↓
Assign attribute values
↓
Run validation
↓
Check if attribute is present?
No→Add error message
Yes↓
Validation passes
↓
Save or reject model
This flow shows how Rails checks if a required attribute is present before saving a model.
Execution Sample
Ruby on Rails
class User < ApplicationRecord
  validates :name, presence: true
end

user = User.new(name: "")
user.valid?
This code creates a User model that requires a name to be present and checks if an empty name is valid.
Execution Table
StepAttribute 'name' ValueValidation CheckResultError Messages
1""Is 'name' present?No["Name can't be blank"]
2"Alice"Is 'name' present?Yes[]
3nilIs 'name' present?No["Name can't be blank"]
4"Bob"Is 'name' present?Yes[]
5Validation stopsAll attributes checkedValidation passes only if all presentErrors prevent save
💡 Validation stops after checking presence; if any required attribute is missing, errors block saving.
Variable Tracker
VariableStartAfter 1After 2After 3After 4Final
user.namenil"""Alice"nil"Bob""Bob"
user.errors[:name][]["Name can't be blank"][]["Name can't be blank"][][]
user.valid?falsefalsetruefalsetruetrue
Key Moments - 3 Insights
Why does an empty string fail presence validation?
Presence validation treats empty strings as missing values, so it adds an error as shown in step 1 of the execution_table.
What happens if the attribute is nil?
If the attribute is nil, presence validation fails and adds an error, as shown in step 3 of the execution_table.
Does presence validation allow saving if the attribute is present?
Yes, if the attribute is present and not empty, validation passes and the model can be saved, as shown in steps 2 and 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the validation result when user.name is an empty string?
AValidation is skipped
BValidation passes with no errors
CValidation fails with error message
DValidation passes but with warnings
💡 Hint
Check step 1 in the execution_table where user.name is ""
At which step does the validation pass because the name is present?
AStep 2
BStep 1
CStep 3
DStep 5
💡 Hint
Look for steps where validation result is 'Yes' and errors are empty
If user.name is nil, what error message appears according to the execution_table?
A"Name is invalid"
B"Name can't be blank"
CNo error message
D"Name must be unique"
💡 Hint
See step 3 in the execution_table for user.name = nil
Concept Snapshot
Presence validation in Rails ensures a model attribute is not empty or nil.
Use validates :attribute, presence: true in the model.
If the attribute is missing or empty string, validation fails.
Errors are added to the model preventing save.
This helps keep required data present before saving.
Full Transcript
Presence validation in Rails checks if a model attribute has a value before saving. When you add validates :name, presence: true, Rails ensures the name is not nil or an empty string. If the attribute is missing, Rails adds an error message like "Name can't be blank" and the model is invalid. This prevents saving incomplete data. The execution table shows different values for the name attribute and whether validation passes or fails. Empty strings and nil values fail validation, while non-empty strings pass. This simple check helps keep your data complete and reliable.

Practice

(1/5)
1. What does validates :name, presence: true do in a Rails model?
easy
A. It ensures the name field is not empty before saving.
B. It automatically fills the name field with a default value.
C. It deletes the record if name is empty.
D. It allows name to be empty without errors.

Solution

  1. Step 1: Understand presence validation purpose

    Presence validation checks that a field is not blank before saving a record.
  2. Step 2: Apply to name field

    Using validates :name, presence: true means the name must have a value.
  3. Final Answer:

    It ensures the name field is not empty before saving. -> Option A
  4. Quick Check:

    Presence validation = field not empty [OK]
Hint: Presence validation means field cannot be blank [OK]
Common Mistakes:
  • Thinking it fills default values automatically
  • Confusing presence with uniqueness validation
  • Assuming it deletes records if empty
2. Which of the following is the correct syntax to add presence validation for the email attribute in a Rails model?
easy
A. validates_presence_of email
B. validates :email, presence: true
C. validate :email, presence: true
D. validates :email, required: true

Solution

  1. Step 1: Recall modern Rails validation syntax

    Rails uses validates :attribute, presence: true for presence validation.
  2. Step 2: Check each option

    validates_presence_of email is invalid syntax (missing symbol ":email"); validates :email, presence: true is the correct modern syntax; validate :email, presence: true is incorrect method name; validates :email, required: true uses wrong option key.
  3. Final Answer:

    validates :email, presence: true -> Option B
  4. Quick Check:

    Use validates :field, presence: true [OK]
Hint: Use validates :field, presence: true for presence [OK]
Common Mistakes:
  • Using validate instead of validates
  • Using required instead of presence
  • Confusing old and new syntax
3. Given this model code:
class User < ApplicationRecord
  validates :username, presence: true
end

What happens if you try to save User.new(username: '')?
medium
A. The save fails because username is blank.
B. The user is saved with an empty username.
C. An error is raised due to syntax error.
D. The username is automatically set to 'default'.

Solution

  1. Step 1: Understand presence validation effect on blank string

    Presence validation treats empty strings as invalid, so saving fails.
  2. Step 2: Apply to username: ''

    Since username is empty string, validation fails and save returns false.
  3. Final Answer:

    The save fails because username is blank. -> Option A
  4. Quick Check:

    Empty string fails presence validation [OK]
Hint: Empty string fails presence validation, save returns false [OK]
Common Mistakes:
  • Thinking empty string passes presence validation
  • Expecting automatic default value assignment
  • Confusing validation failure with exceptions
4. Identify the error in this model validation code:
class Product < ApplicationRecord
  validates :title, presence
end
medium
A. No error, code is correct.
B. Should use validate instead of validates.
C. The attribute title must be a string.
D. Missing true after presence.

Solution

  1. Step 1: Check presence validation syntax

    Presence validation requires presence: true, not just presence.
  2. Step 2: Identify missing true

    The code misses : true after presence, causing syntax error.
  3. Final Answer:

    Missing true after presence. -> Option D
  4. Quick Check:

    Presence validation needs presence: true [OK]
Hint: Always write presence: true for presence validation [OK]
Common Mistakes:
  • Omitting : true after presence
  • Using validate instead of validates
  • Assuming attribute type affects validation syntax
5. You want to ensure a Post model's title and content are present, but content can be blank if title is 'Draft'. Which validation setup achieves this?
hard
A. validates :title, presence: true validates :content, presence: false, unless: -> { title == 'Draft' }
B. validates :title, presence: true validates :content, presence: true, if: -> { title == 'Draft' }
C. validates :title, presence: true validates :content, presence: true, unless: -> { title == 'Draft' }
D. validates :title, presence: true validates :content, presence: false, if: -> { title == 'Draft' }

Solution

  1. Step 1: Understand requirement for content

    Content must be present except when title is 'Draft'.
  2. Step 2: Use conditional presence validation

    Use presence: true with unless condition to skip validation if title is 'Draft'.
  3. Step 3: Check options

    validates :title, presence: true validates :content, presence: true, unless: -> { title == 'Draft' } correctly uses unless: -> { title == 'Draft' } to skip content presence validation when title is 'Draft'. Others misuse if or set presence false incorrectly.
  4. Final Answer:

    validates :title, presence: true validates :content, presence: true, unless: -> { title == 'Draft' } -> Option C
  5. Quick Check:

    Use unless to skip presence validation conditionally [OK]
Hint: Use unless to skip presence validation conditionally [OK]
Common Mistakes:
  • Using if instead of unless for skipping validation
  • Setting presence: false which disables validation
  • Not combining validations properly
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