0
0
Ruby on Railsframework~30 mins

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

Choose your learning style9 modes available
Numericality Validation in Rails Model
📖 Scenario: You are building a simple Rails application to manage products. Each product has a price that must be a number. To keep data clean, you want to ensure that the price is always a number when saving a product.
🎯 Goal: Learn how to add numericality validation to a Rails model attribute to ensure only numbers are accepted.
📋 What You'll Learn
Create a Rails model called Product with an attribute price
Add a numericality validation to the price attribute
Allow only numeric values for price
Ensure the validation is active when saving a product
💡 Why This Matters
🌍 Real World
Validations like numericality ensure that data entered into your app is correct and prevents errors later on.
💼 Career
Rails developers often add validations to models to enforce business rules and data integrity.
Progress0 / 4 steps
1
Create the Product model with a price attribute
Create a Rails model called Product with an attribute price of type decimal.
Ruby on Rails
Need a hint?

Use rails generate model Product price:decimal to create the model and migration.

2
Add a numericality validation configuration
Inside the Product model, add a validation line that sets up numericality validation for the price attribute.
Ruby on Rails
Need a hint?

Use validates :price, numericality: true inside the model class.

3
Test the numericality validation in the model
Write a method inside the Product model called valid_price? that returns true if the product is valid and false otherwise, using the built-in valid? method.
Ruby on Rails
Need a hint?

Use def valid_price? and inside it call valid? to check validations.

4
Complete the model with validation and method
Ensure the Product model includes the price attribute, the numericality validation, and the valid_price? method as defined.
Ruby on Rails
Need a hint?

Make sure all parts are present: class, validation, and method.