How to create, handle and validate forms in Ruby on Rails?
Forms are one of the basic elements of any web application because they allow for information submission, such as name, email address, phone number, and other required information whether one is signing up for a new account, sending a contact form, or posting news updates. These factors make Ruby on Rails highly popular in managing and working with forms because it is equipped with its own built-in features and helpers, making the process of building, submitting, and validating a form less difficult.
In this article, we will see each aspect of working on a form in Rails-from building to its validation while keeping it secure and an excellent user experience.
Table of Content
What Are Forms in Rails?
In Rails, forms are also used to extract data from users and then send that data on to the server. The form helpers in Rails make it a very simple task to create forms since they automatically generate the correct HTML and take care of security concerns like CSRF protection. Form helpers even let you tie your forms directly to your models so that your view and backend logic integrate transparently with each other.
Importance of Form Handling and Validation
A form handling feature extends beyond capturing data and also includes managing form submission, sanitizing the input of users, along with providing immediate feedback to the user once there are errors. Validations also play a significant role in ensuring that data presented is correct and subject to the necessary conditions before saving in the database. Otherwise, your application would be prone to bad data and security risks.
Creating Forms in Rails
Rails provides many forms helpers to ease the process of building forms. The most commonly used helper is the form_with, which will bind a form to an active record model.
Example:
Let's create a form for adding a new user. In your view (new.html.erb):
<% if @user.errors.any? %>
<div id="error_explanation" style="color: red; border: 1px solid red; padding: 3px; background-color:
#f8d7da; border-radius: 4px; margin-bottom: 5px;">
<h2 style="font-size: 12px; margin: 0;"><%= pluralize(@user.errors.count, "error") %>
prohibited this user from being saved:</h2>
<ul style="padding-left: 10px; margin: 0;">
<% @user.errors.full_messages.each do |message| %>
<li style="font-size: 12px;"><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= form_with model: @user, local: true do |form| %>
<!-- Name Field -->
<div>
<%= form.label :name %><br>
<%= form.text_field :name, style:
"width: auto; padding: 2px; border: 1px solid black;" %>
<% if @user.errors[:name].any? %>
<div style="color: red; font-size: 10px;"><%= @user.errors[:name].first %></div>
<% end %>
</div>
<!-- Email Field -->
<div style="margin-bottom: 8px;"> <!-- Added small margin for spacing -->
<%= form.label :email %><br>
<%= form.text_field :email, style:
"width: auto; padding: 2px; border: 1px solid black;" %>
<% if @user.errors[:email].any? %>
<div style="color: red; font-size: 10px;"><%= @user.errors[:email].first %></div>
<% end %>
</div>
<!-- Submit Button -->
<div>
<%= form.submit "Create User", style:
"padding: 2px 4px; background-color: #ffffff; border: 1px solid black; cursor: pointer;" %>
</div>
<% end %>
Explanation:
- form_with creates a form.
- model: @user binds the form to the @user object, which is an instance of the User model.
- form.label and form.text_field create labels and input fields for user attributes.
- form.submit: This generates a submit button that sends the form data to the server
Rails automatically includes CSRF tokens to protect from cross-site request forgery.
Output
This form allows users to enter their name and email.
<img src="C:\Users\sivam\converted_image.webp"
alt="User form with fields for name and email, and a 'Create User' button" />
<figcaption>A simple Rails form for creating a
user with fields for name, email, and a submit button.</figcaption>

Form Structure and Elements
Rails form consists of several elements:
- Form Tag: It gets generated by the form_with method and spans over all the form elements.
- Input Fields: For each attribute (e.g., name, email) , Rails generates a corresponding input field with the proper id and name attributes that makes it a lot easier to process them at the back end.
- Submit Button: Rails gives you the feature of using a submit button that will automatically submit the form.
Handling Form Submissions
When the form is submitted, it sends the data to the controller where you process it. In our example, it will be the UsersController that receives the data.
Example:
Here’s how you would handle your form submissions in your controller:
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
redirect_to @user, notice: 'User was successfully created.'
else
render :new
end
end
private
def user_params
params.require(:user).permit(:name, :email)
end
end
Explanation:
- A new action initializes an empty @user object for the form.
- The create action accepts the form data via the user_params method, saves @user to the database, and redirects if the save was successful; otherwise, it re-renders the form.
- user_params ensures only the allowed attributes (:name, :email) are passed to avoid mass-assignment vulnerabilities.
Output:
<img src="C:\Users\sivam\Screenshot 2024-10-12 222342.webp"
alt="Success message displayed on a user creation form with input
fields for name and email.">
<figcaption>A web form showing the message
'User was successfully created' with name and email fields below.</figcaption>

Validating Forms Inputs
Validations check to ensure that the input to a form is correct before it saves them to the database. Rails has provided several easy ways to implement model-level validations.
Example:
Let's add validations to our User model:
class User < ApplicationRecord
validates :name, presence: true, length: { minimum: 2 }
validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
end
Explanation
- validates :name, presence: true ensures that the field is filled in with name.
- length: { minimum: 2 } Makes sure the name contains at least two characters.
- validates :email, format: { with: URI::MailTo::EMAIL_REGEXP } — requires a presence and valid email format.
When the form is submitted, data that fails the validations will automatically trigger error messages displayed in the view by Rails.
Displaying Validation Errors
When a form fails validation, Rails automatically provides error messages, which you can display in the view.
Example:
In your new.html.erb form, you can display the validation errors like this:
<% 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 %>
This will display a list of errors on the form page when the user submits invalid data.
Output:
<img src="C:\Users\sivam\Screenshot 2024-10-12 220618.webp" alt="Form submission error message with validation issues for the email field" />
<figcaption>Form submission error showing that the email field can't be blank and must be valid in a Rails application.</figcaption>

Best Practices
- Strong Parameters: Always use strong parameters to whitelist the allowed form inputs.
- Model Validations: Keep validations in the model so you cannot save invalid data even outside of a form context
- Error Handling: Display helpful error messages to guide users when their submissions fail
- Security: Rails automatically handles CSRF protection, but again it's good to know where you can find security best practices when dealing with users.
Conclusion
Ruby on Rails makes handling forms easier with the embedded helpers and validation. If implemented in the following steps from this article, a developer would be able to build solid forms, handle their submissions efficiently, validate data before saving it into the database, and generally enjoy the ease and security that Rails' conventions and helpers add to the process of form handling in Rails applications.