Open In App

CRUD Operation in Ruby on Rails

Last Updated : 16 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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/

crud

2. Create a new post http://localhost:3000/posts/new

Screenshot-2024-09-25-110205
new post

3. Show a specific post http://localhost:3000/posts/1

Screenshot-2024-09-25-110521
show post

4. Update a post http://localhost:3000/posts/1/edit

Screenshot-2024-09-25-110646
edit post

5. Delete a post click on delete button

Screenshot-2024-09-25-112756
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.


Next Article
Article Tags :

Similar Reads