CRUD Operation in Ruby on Rails
Last Updated :
16 Oct, 2024
In Ruby on Rails, CRUD stands for Create, Read, Update, and Delete the four basic operations for managing data in most web applications. Rails makes implementing CRUD functionality very straightforward using its MVC (Model-View-Controller) architecture.
What is CRUD?
CRUD stands for Create, Read, Update, and Delete, the four fundamental operations used to manage data in a database or a web application.
- Create: Adding new data to the system (e.g., creating a new record).
- Read: Retrieving or displaying data (e.g., viewing a record).
- Update: Modifying existing data (e.g., editing a record).
- Delete: Removing data from the system (e.g., deleting a record).
These operations form the backbone of most applications that interact with a database.
Importance of CRUD in Web Applications
CRUD operations are essential in web applications because they define the core interactions between users and data. Here’s why CRUD is important:
- Fundamental Data Management: CRUD operations allow users to perform the basic tasks of data manipulation, creating, reading, updating, and deleting records. Without CRUD, it would be impossible to interact with the database effectively.
- User Interaction: Web applications often require user input or actions to manage data, and CRUD operations enable this interaction. Users can add new items (e.g., sign up, submit forms), view data (e.g., product listings), modify existing data (e.g., profile updates), or delete information (e.g., remove account or files).
- Consistency: CRUD ensures data consistency by providing a structured way to handle database changes. It defines how new data enters the system, how it is accessed, and how updates or deletions are carried out without breaking data integrity.
- Efficiency in Development: Implementing CRUD operations allows developers to quickly build and maintain dynamic web applications. Most web frameworks, like Ruby on Rails, provide built-in support for CRUD, speeding up the development process.
- Data Security: By defining clear operations for data management, CRUD helps enforce security policies (e.g., only allowing authenticated users to modify or delete data).
Setting Up your Rails Environment
Make sure you have Ruby and Rails installed on your system. You can istall Rails using the following command:
gem install rails
In Ruby on Rails, CRUD stands for Create, Read, update, and Delete the basic operations for interacting with a database. Here’s a simple example of how you can performed these operations in Rails app.
Set Up a New Rails Project: Create a new project using a command
rails new blog_gfg
cd blog_gfg
Generating a Scaffold for CRUD Operation
Use the scaffold generator to create a Post resource with attributes such as title and body.
rails generate scaffold Post title:string body:text
This command does the following:
- Creates a model (app/models/post.rb)
- Creates a migration for the database table (db/migrate/...create_posts.rb)
- Creates a controller (app/controllers/posts_controller.rb)
- Generates views for each CRUD action in app/views/posts/
- Configures the routes for Post in config/routes.rb
Database Migration in Ruby on Rails
Run the migration to apply the changes to the database.
rails db:migrate
This creates a posts table with title and body columns.
Creating Records in Ruby on Rails
The create action handles the creation of a new record. This is done by submitting a form.
Form for new post (app/views/posts/new.html.erb):
HTML
<%= form_with model: @post, local: true do |form| %>
<div>
<%= form.label :title %>
<%= form.text_field :title %>
</div>
<div>
<%= form.label :body %>
<%= form.text_area :body %>
</div>
<div>
<%= form.submit "Create Post" %>
</div>
<% end %>
Controller logic (app/controllers/posts_controller.rb):
Ruby
def create
@post = Post.new(post_params)
if @post.save
redirect_to @post, notice: 'Post was successfully created.'
else
render :new
end
end
The form sends a POST request to the create action, which initializes a new post and attempts to save it to the database. If validation passes, the post is saved; otherwise, the form is re-rendered with error messages.
Reading Records in Ruby on Rails
The index and show actions are used to read data.
List all posts (app/views/posts/index.html.erb)
HTML
<h1>Posts</h1>
<%= link_to 'New Post', new_post_path %>
<ul>
<% @posts.each do |post| %>
<li>
<%= link_to post.title, post %>
<%= link_to 'Edit', edit_post_path(post) %> |
<%= link_to 'Delete', post, method: :delete, data: { confirm: 'Are you sure?' } %>
</li>
<% end %>
</ul>
Show a single post (app/views/posts/show.html.erb)
HTML
<h1><%= @post.title %></h1>
<p><%= @post.body %></p>
<%= link_to 'Edit', edit_post_path(@post) %> |
<%= link_to 'Back', posts_path %>
Controller logic for reading data (app/controllers/posts_controller.rb)
Ruby
def index
@posts = Post.all
end
def show
@post = Post.find(params[:id])
end
The index action fetches all posts from the database, and the show action retrieves a specific post using its ID.
Updating Records in Ruby on Rails
The edit and update actions handle the modification of a post.
Form for editing a post (app/views/posts/edit.html.erb)
HTML
<%= form_with model: @post, local: true do |form| %>
<div>
<%= form.label :title %>
<%= form.text_field :title %>
</div>
<div>
<%= form.label :body %>
<%= form.text_area :body %>
</div>
<div>
<%= form.submit "Update Post" %>
</div>
<% end %>
Controller logic for updating (app/controllers/posts_controller.rb)
Ruby
def edit
@post = Post.find(params[:id])
end
def update
@post = Post.find(params[:id])
if @post.update(post_params)
redirect_to @post, notice: 'Post was successfully updated.'
else
render :edit
end
end
The edit action displays the form pre-filled with the current post data, and the update action processes the form submission to update the post.
Deleting Records in Ruby on Rails
The destroy action handles deleting a post.
Controller logic for deletion (app/controllers/posts_controller.rb)
Ruby
def destroy
@post = Post.find(params[:id])
@post.destroy
redirect_to posts_url, notice: 'Post was successfully deleted.'
end
The destroy method finds the post by its ID and deletes it from the database. A confirmation dialog is shown to the user before proceeding.
Routing CRUD Operations in Ruby on Rails
Rails automatically configures the routes for all CRUD operations when you generate the scaffold. These routes are defined in config/routes.rb as:
resources :posts
These will generate the various routing:
HTTP verb | Path | Controller Action | Description |
---|
GET | /posts | index | List of all post |
---|
GET | /posts/new | new | form for new post |
---|
POST | /posts | create | Create a new post |
---|
GET | /posts/:id | show | show a specific post |
---|
GET | /posts/:id/edit | edit | Form to edit |
---|
PATCH/PUT | /posts/:id | update the post | update the post |
---|
DELETE | /posts/:id | destroy | Delete the post |
---|
Implementing Validations and Callbacks
To ensure that the title and body of the post are always present, add validation to the model.
Model validation (app/models/post.rb)
Ruby
class Post < ApplicationRecord
validates :title, presence: true, length: { minimum: 5 }
validates :body, presence: true
# Callback example
before_save :capitalize_title
private
def capitalize_title
self.title = title.capitalize
end
end
In this example:
- validates :title, presence: true, length: { minimum: 5 }: Ensures that the title is not empty and is at least 5 characters long.
- validates :body, presence: true: Ensures that the body is not empty
Callback:
- A callback is a method triggered during the lifecycle of an ActiveRecord object (e.g., before saving, after destroying).
- Before Save Callback: The capitalize_title method is called before saving the post to capitalize the title.
Testing CRUD Operation
1. Testing you rails application and perform crud operation in your browser in http://localhost:3000/
2. Create a new post http://localhost:3000/posts/new
new post3. Show a specific post http://localhost:3000/posts/1
show post4. Update a post http://localhost:3000/posts/1/edit
edit post5. Delete a post click on delete button
delete post
Conclusion
In conclusion, using Rails scaffolding simplifies the process of generating a fully functional CRUD application, enabling rapid development with minimal setup. It provides automatic routing, controller actions, and views for managing resources, making it ideal for prototyping or small projects. With the addition of validations, you can enforce data integrity, ensuring that only correct and complete information is saved. Callbacks enhance flexibility, allowing you to customize the behavior of models during lifecycle events such as saving, updating, or deleting. Together, these features provide a robust framework for building and managing data-driven applications in Ruby on Rails.
Similar Reads
Ruby on Rails - Controller
In Ruby on Rails, a Controller manages the flow of data between the Model and the View. When a user makes a request, the Controller decides what data to fetch or update, and which view to display. Think of it as the middleman that takes user input, processes it with the help of the Model, and sends
6 min read
Ruby | Rational rational() function()
The Rational() is an inbuilt method in Ruby returns the rational number of the form a/b. Syntax: Rational(num, den) Parameters: The function accepts two parameters which represents numerator and denominator. By default, the denominator is 1. Return Value: It returns the rational number of the form a
1 min read
Ruby on Rails Introduction
Ruby on Rails or also known as rails is a server-side web application development framework that is written in the Ruby programming language, and it is developed by David Heinemeier Hansson under the MIT License. It supports MVC(model-view-controller) architecture that provides a default structure f
6 min read
Ruby | Rational inspect() function
The inspect() is an inbuilt function in Ruby returns the value as a string. Syntax: rat.inspect() Parameters: The function accepts no parameter Return Value: It returns the value as a string Example 1: Ruby # Ruby program for inspect() method # Initialize rational number rat1 = Rational(8, -6) # Pri
1 min read
Ruby | Rational ceil() function
The ceil() is an inbuilt function in Ruby returns the smallest number greater than or equal to rat with a precision of ndigits decimal digits. ndigits by default is 0. It returns a rational when ndigits is positive, otherwise returns an integer. Syntax: rat.ceil(ndigits) Parameters: The function acc
1 min read
Ruby on Rails - Active Job
Active Job is a framework in Ruby on Rails designed to handle background jobs. Background jobs are tasks that can be processed asynchronously, allowing your application to remain responsive while performing time-consuming operations behind the scenes. Active Job makes it easy to manage these tasks,
9 min read
Ruby on Rails - Caching
Ruby on Rails provides a set of powerful caching mechanisms that can significantly help optimize the performance of web applications, which rely heavily on database operations and rendering. Caching in Rails means storing the result of expensive operations such as database lookups or complex view re
11 min read
Layouts in Ruby on Rails
In Ruby on Rails, a layout is like a template that wraps around your pages. This will give all your web pages an understandable structure so that the header, footer, and the rest of the design look the same on every page. Rails has a default layout named application.html.erb, which can be found in t
6 min read
Ruby | Rational rationalize() function
The rationalize() is an inbuilt function in Ruby returns a simpler approximation of the value if the optional argument eps is given (rat-|eps| <= result <= rat+|eps|) otherwise returns its self. Syntax: rat.rationalize(eps) Parameters: The function accepts a single optional parameter Return Va
1 min read
Ruby | Rational positive?() function
The positive?() is an inbuilt function in Ruby returns boolean value true if rational number is greater than zero otherwise false Syntax: rat.positive?() Parameters: The function accepts no parameter Return Value: It returns boolean value true if rational number is greater than zero otherwise false
1 min read