Conditional Validations in Rails Model
📖 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