0
0
Ruby on Railsframework~30 mins

Conditional validations in Ruby on Rails - Mini Project: Build & Apply

Choose your learning style9 modes available
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
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
Need a 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
Need a 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
Need a 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
Need a hint?

The initialize method sets instance variables from the given hash keys.