Ruby on Rails / CRUD Operations in Rails

Handling Forms and User Input

In this tutorial, you'll learn how to handle user input through forms in a Rails application. You'll learn how to capture and process form data to perform CRUD operations.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explains how to perform CRUD (Create, Read, Update, Delete) operations in Rails.

Handling Forms and User Input in Rails

1. Introduction

In this tutorial, we are going to explore how to handle user input through forms in a Rails application. We will capture and process form data to perform CRUD operations (Create, Read, Update, Delete).

By the end of this tutorial, you will be able to:

  • Understand how forms work in Rails
  • Create a form to accept user input
  • Validate the data received from a form
  • Save the data to a database

Prerequisites:
- Basic understanding of Ruby and Rails
- Rails installed on your machine
- Basic knowledge of HTML

2. Step-by-Step Guide

Rails provide several helpers to work with forms. The most common one is form_with.

form_with

form_with is a form builder provided by Rails. It's a method that accepts a block of code, which describes the contents of the form.

<%= form_with do |form| %>
  ...
<% end %>

Inside the block, you can use other form helpers to create fields. For example, form.text_field creates a text field, form.label creates a label, and form.submit creates a submit button.

<%= form_with do |form| %>
  <%= form.label :name, 'Your Name:' %>
  <%= form.text_field :name %>
  <%= form.submit 'Submit' %>
<% end %>

Form Data Processing

When the form is submitted, the data is sent to the server. In Rails, you typically define a route, a controller, and an action to handle the form data.

# routes.rb
resources :users, only: [:new, :create]

# users_controller.rb
def create
  @user = User.new(user_params)
  if @user.save
    redirect_to @user
  else
    render 'new'
  end
end

private

def user_params
  params.require(:user).permit(:name)
end

3. Code Examples

Let's create a form for a User model. Our User model has a name and email.

# app/models/user.rb
class User < ApplicationRecord
  validates :name, presence: true
  validates :email, presence: true
end

Now, let's create a new view with a form to create a new user.

# app/views/users/new.html.erb
<%= form_with model: @user do |form| %>
  <%= form.label :name %>
  <%= form.text_field :name %>

  <%= form.label :email %>
  <%= form.text_field :email %>

  <%= form.submit %>
<% end %>

Finally, let's create the new and create actions in UsersController.

# app/controllers/users_controller.rb
class UsersController < ApplicationController
  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
      redirect_to @user
    else
      render 'new'
    end
  end

  private

  def user_params
    params.require(:user).permit(:name, :email)
  end
end

4. Summary

In this tutorial, we learned how to handle forms in Rails. We learned about the form_with helper, how to create different form fields, and how to process form data in a controller.

To further your learning, practice creating forms for different models, and try using different form helpers.

Some useful resources:
- Rails Guide: Form Helpers
- Rails API Documentation: form_with

5. Practice Exercises

  1. Create a form for a Product model with name, description, and price fields.
  2. Add validation to the Product model. name and price should be required, and price should be a number greater than 0.
  3. In the ProductsController, create new and create actions to handle the form data.

For further practice, try creating a form to update an existing record, and an action in the controller to handle the update request.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

Open Graph Preview Tool

Preview and test Open Graph meta tags for social media.

Use tool

Image Compressor

Reduce image file sizes while maintaining quality.

Use tool

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

Random Password Generator

Create secure, complex passwords with custom length and character options.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help