0
0
Ruby on Railsframework~30 mins

Presence validation in Ruby on Rails - Mini Project: Build & Apply

Choose your learning style9 modes available
Presence Validation in Rails Model
📖 Scenario: You are building a simple Rails application to manage a list of books. Each book must have a title and an author. To ensure data quality, you want to make sure that no book can be saved without these details.
🎯 Goal: Create a Rails model Book with presence validation for the title and author attributes. This will prevent saving books without these required fields.
📋 What You'll Learn
Create a Book model with title and author attributes
Add presence validation for title and author
Use Rails validation syntax correctly
Ensure the model is ready to reject invalid records missing these fields
💡 Why This Matters
🌍 Real World
Presence validation is essential in web apps to ensure users provide required information before saving data, preventing incomplete or invalid records.
💼 Career
Understanding and implementing validations is a fundamental skill for Rails developers to maintain data integrity and build reliable applications.
Progress0 / 4 steps
1
Create the Book model with attributes
Create a Rails model called Book with string attributes title and author using attr_accessor.
Ruby on Rails
Need a hint?

Use attr_accessor to create getter and setter methods for title and author.

2
Add ActiveModel inclusion and validation setup
Include ActiveModel::Model in the Book class to enable validations. Then, add a validation for presence of title and author using validates.
Ruby on Rails
Need a hint?

Use include ActiveModel::Model to add validation features. Then use validates :attribute, presence: true for each attribute.

3
Create a new Book instance with missing title
Create a new instance of Book called book with author set to 'Jane Austen' and title set to nil.
Ruby on Rails
Need a hint?

Use Book.new with keyword arguments to set title to nil and author to 'Jane Austen'.

4
Check if the book instance is valid
Call book.valid? to check if the book instance passes the presence validations.
Ruby on Rails
Need a hint?

Use the valid? method on the book instance to trigger validations.