Ruby on Rails (often just Rails) is a popular web application framework written in Ruby. One of its core features is validation, which ensures that data entered into a Rails application meets specific criteria before being saved to the database. Validations help maintain data integrity, enhance user experience, and prevent invalid or incomplete data from being processed.
What is Validation in Ruby on Rails?
Validation in Ruby on Rails is a mechanism to enforce rules on the data within your application's models. It ensures that data conforms to certain rules before it is saved to the database. This is crucial for maintaining the consistency and accuracy of the data your application handles.
- Data Integrity: Validation helps to ensure that the data entering the system adheres to specific criteria and constraints, preventing the storage of incorrect or incomplete data.
- User Feedback: It helps to provide meaningful error messages to users when they submit invalid data, improving user experience.
- Before Saving: Validations are performed before the data is saved to the database. If any validation fails, the data is not saved, and the object is returned with errors.
- Model-Level Validation: Validations are defined within model classes in Rails. When an object is created or updated, Rails runs these validations to check if the data meets the specified rules.
Built-in Validation Methods
Rails provides several built-in validation methods that you can use to validate your data. Let’s see some of the most common ones.
- 'presence: true': Ensures that a field is not empty.
- 'uniqueness: true': Ensures that a field's value is unique across the database.
- 'length: { minimum: x, maximum: y }': Validates the length of a field's value.
- 'numericality: true': Ensures that a field contains only numbers.
- 'format: { with: regex }': Validates that a field's value matches a specific pattern.
- 'inclusion: { in: range }': Validates that a field's value is included in a given set or range.
Implementing Validation Methods
Let's create a simple demo application to see these validations in action. We’ll build a basic application to manage users.
Step 1: Create a New Rails Application
Create a demo application using the below command.
rails new validation_demo cd validation_demo
Create a Rails AppStep 2: Generate a User Model
Run the following command to generate a 'User' model with a few fields.
rails generate model User name:string email:string age:integer gender:string password:string
User ModelThen, migrate the database,
rails db:migrate
Database MigrationStep 3: Add Validations to the User Model
Open the 'app/models/user.rb' file and add the following validations.
Ruby
class User < ApplicationRecord
validates :name, presence: { message: "can't be blank" }
validates :email, presence: { message: "can't be blank" },
uniqueness: { message: "has already been taken" },
format: { with: /\A[\w\.-]+@[\w\.-]+\.[a-zA-Z]{2,}\z/, message: "is not a valid email address" }
validates :age, numericality: { greater_than_or_equal_to: 18, message: "must be at least 18" }
validates :gender, inclusion: { in: %w(Male Female Non-binary Other), message: "%{value} is not a valid gender" }
validates :password, length: { minimum: 6, maximum: 12, message: "must be between 6 and 12 characters" }
end
Here’s what each validation does:
- Name: Must be present (not empty).
- Email: Must be present, unique, and formatted as a valid email address using the regular expression.
- Age: Must be a number and at least 18 years old.
- Gender: Must be a value from available options.
- Password: Must be at least 6 characters long and a maximum of 12 characters.
Next, let’s create a form for users to sign up. Start by generating a 'UsersController'.
rails generate controller Users new create show
User ControllerThen, in the 'app/controllers/users_controller.rb' file, add the following.
Ruby
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
redirect_to user_path(@user)
else
render :new
end
end
def show
@user = User.find(params[:id])
end
private
def user_params
params.require(:user).permit(:name, :email, :age, :gender, :password)
end
end
Next, create a view for the 'new' action in 'app/views/users/new.html.erb'.
HTML
<h1>New User</h1>
<%= form_with model: @user, local: true do |form| %>
<% if @user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>
<ul>
<% @user.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :name %>
<%= form.text_field :name %>
</div>
<div class="field">
<%= form.label :email %>
<%= form.text_field :email %>
</div>
<div class="field">
<%= form.label :age %>
<%= form.number_field :age %>
</div>
<div class="field">
<%= form.label :gender %>
<%= form.select :gender, options_for_select(['Male', 'Female', 'Non-binary', 'Other']) %>
</div>
<div class="field">
<%= form.label :password %>
<%= form.password_field :password %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
Next, create a view for the 'new' action in 'app/views/users/show.html.erb'.
HTML
<h1>User Details</h1>
<p>
<strong>Name:</strong>
<%= @user.name %>
</p>
<p>
<strong>Email:</strong>
<%= @user.email %>
</p>
<p>
<strong>Age:</strong>
<%= @user.age %>
</p>
<p>
<strong>Gender:</strong>
<%= @user.gender %>
</p>
<p>
<strong>Password:</strong>
<%= @user.password %>
</p>
This page will be displayed after the successful submission of the form without breaking any validation.
Step 5: Setup Routes
Make changes in 'config/routes.rb' like this,
Ruby
Rails.application.routes.draw do
resources :users, only: [:new, :create, :show]
end
Use the below command to execute the code:
rails server
Output
Each input will be checked according to the validation rules specified in the User model. If any input fails to meet the defined criteria, such as presence, format, or length, then the form will not be submitted. After successful submission, the user data will be visible on the next page. You can use a 'flash' message or JavaScript to display error messages.
Skipping Validations
Skipping validations in Ruby on Rails can be useful in certain scenarios, such as when you need to make a quick update to a record without enforcing all the validations. Here are some examples of how you can skip validations using the Rails console.
1. Skipping Validations with 'save(validate: false)'
You can skip validations when saving a record by passing 'validate: false' to the 'save' method. This tells Rails to save the record without running any validations.
Now, let's create a user in the Rails console.
rails console
Create an object 'user' with record details.
user = User.new(name:"john", email:"[email protected]", age:15, gender:"Male", password:"123")
Try to save it without skipping validations.
user.save
It will give 'false' since the age is less than 18.
Now, save the record while skipping validations.
user.save(validate:false)
See the below output for better understanding:
Skip Validation Using Save(validate:false)2. Skipping Validations with 'update_attribute'
The 'update_attribute' method skips validations for a single attribute and saves the record directly.
Open the rails console and create an object 'user'.
user = User.find_by(email: "[email protected]")
Try to update the age with validation. It will give 'false'.
user.update(age: 12)
Skip validations and update the age.
user.update_attribute(:age, 12)
See the below output for better understanding:
Skip Validation Using update_attributeConclusion
Validation in Ruby on Rails is a powerful tool that helps you ensure data integrity in your applications. With the built-in validation methods, you can easily enforce rules on your data before it gets saved to the database. In this article, we covered the basics of validations, including how to create a simple application with a form that uses various validation methods. With this knowledge, you're ready to start adding validations to your Rails applications.
Related Articles:
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Python Variables In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read
Spring Boot Interview Questions and Answers Spring Boot is a Java-based framework used to develop stand-alone, production-ready applications with minimal configuration. Introduced by Pivotal in 2014, it simplifies the development of Spring applications by offering embedded servers, auto-configuration, and fast startup. Many top companies, inc
15+ min read