📖 Scenario: You are building a simple Rails application to manage user profiles. Some users are students, and some are teachers. You want to make sure that if a user is a student, they must provide their school_name. If the user is a teacher, they must provide their subject. This helps keep your data clean and relevant.
🎯 Goal: Create a Rails model User with conditional validations that require school_name only if the user is a student, and require subject only if the user is a teacher.
📋 What You'll Learn
Create a User model with attributes role, school_name, and subject.
Add a validation that requires school_name only when role is "student".
Add a validation that requires subject only when role is "teacher".
Use Rails built-in validation methods with conditional options.
💡 Why This Matters
🌍 Real World
Conditional validations are common in real apps where certain fields are required only in specific situations, like user roles or product types.
💼 Career
Understanding conditional validations helps you write flexible and robust Rails models, a key skill for backend web development jobs.
Progress0 / 4 steps
1
Create the User model with attributes
Create a Rails model class called User with attributes role, school_name, and subject defined as attr_accessors.
Ruby on Rails
Hint
Use attr_accessor to create getter and setter methods for the attributes.
2
Add role constants for clarity
Inside the User class, add two constants: STUDENT_ROLE set to "student" and TEACHER_ROLE set to "teacher".
Ruby on Rails
Hint
Constants are written in uppercase letters and help avoid magic strings.
3
Add conditional validations for school_name and subject
Add validations inside the User class: validate presence of school_name only if role equals STUDENT_ROLE, and validate presence of subject only if role equals TEACHER_ROLE. Use the if: option with lambda functions.
Ruby on Rails
Hint
Use validates :attribute, presence: true, if: -> { condition } to add conditional validations.
4
Add initialize method to set attributes
Add an initialize method to the User class that accepts a hash with keys :role, :school_name, and :subject and sets the corresponding instance variables.
Ruby on Rails
Hint
The initialize method sets instance variables from the given hash keys.
Practice
(1/5)
1. What does a conditional validation in Rails do?
easy
A. Runs validation only when a specific condition is true
B. Runs validation on every save regardless of conditions
C. Disables all validations temporarily
D. Automatically fixes invalid data
Solution
Step 1: Understand the purpose of conditional validations
Conditional validations allow validations to run only if certain conditions are met, making them flexible.
Step 2: Compare options with this purpose
Only Runs validation only when a specific condition is true describes running validation based on a condition, matching the concept.
Final Answer:
Runs validation only when a specific condition is true -> Option A
Quick Check:
Conditional validation = run if condition true [OK]
Hint: Conditional validations run only when conditions are true [OK]
Common Mistakes:
Thinking validations always run on every save
Confusing conditional validations with disabling validations
Believing validations fix data automatically
2. Which of the following is the correct syntax to add a conditional validation using if with a method named active??
easy
A. validates :name, presence: true if :active?
B. validates :name, presence: true, if: :active?
C. validates :name, presence: true, if active?
D. validates :name, presence: true, if => :active?
Solution
Step 1: Recall correct syntax for conditional validations
Rails uses a hash key if: followed by a symbol or lambda for conditions.
Step 2: Match options with correct syntax
validates :name, presence: true, if: :active? correctly uses if: :active?. Others have syntax errors or missing commas.
Final Answer:
validates :name, presence: true, if: :active? -> Option B
Quick Check:
Use if: :method_name for conditional validation [OK]
Hint: Use if: :method_name with a comma for conditional validations [OK]
Common Mistakes:
Omitting comma before if
Using if without colon or symbol
Using wrong hash rocket syntax
3. Given this model code:
class User < ApplicationRecord
validates :email, presence: true, unless: :guest?
def guest?
role == 'guest'
end
end
What happens when you save a User with role = 'guest' and email = nil?
medium
A. Validation fails because role is not checked
B. Validation fails because email is missing
C. Raises an error due to missing email
D. Validation passes because guest users skip email validation
Solution
Step 1: Understand the conditional validation with unless
The validation runs unless the guest? method returns true. If user is guest, validation is skipped.
Step 2: Apply to given user data
User has role 'guest', so guest? returns true, skipping email presence validation. So saving passes despite missing email.
Final Answer:
Validation passes because guest users skip email validation -> Option D
Quick Check:
unless: :guest? skips validation if guest? true [OK]
Hint: unless skips validation when condition method returns true [OK]
Common Mistakes:
Assuming validation always runs regardless of unless
C. Using method call instead of symbol for if condition
D. numericality should be a method, not an option
Solution
Step 1: Check syntax for conditional validation if option
The if: option expects a symbol or lambda, not a method call.
Step 2: Analyze given code
Here, user.adult? is a method call, which is invalid syntax in validation options.
Final Answer:
Using method call instead of symbol for if condition -> Option C
Quick Check:
Use symbol (:method_name), not method call, for if condition [OK]
Hint: Use :method_name symbol, not method call, in if condition [OK]
Common Mistakes:
Calling method instead of passing symbol
Confusing method call with symbol
Ignoring syntax errors in validation options
5. You want to validate presence of phone_number only if the user is an admin or if the account is active. Which is the correct way to write this conditional validation?