Performing CRUD Operations in Rails

Tutorial 1 of 5

1. Introduction

Goal

This tutorial aims to guide you through performing Create, Read, Update, and Delete (CRUD) operations in Rails, which are fundamental to most web applications.

Learning Outcome

By the end of this tutorial, you will be proficient in performing CRUD operations in Rails.

Prerequisites

  • Basic understanding of Rails
  • Ruby and Rails installed on your machine
  • A text editor (e.g., VS Code, Sublime Text)

2. Step-by-Step Guide

CRUD operations are basic data manipulation for Database. CRUD stands for Create, Read, Update, and Delete. Let's understand each operation one by one.

Create

Creating new data in Rails is straightforward. First, you need to initiate a new instance of the model, assign values to the instance variables, and then call the save method.

post = Post.new
post.title = "My First Post"
post.save

Read

Reading data from a database in Rails can be done in several ways. The most common method is using the find, find_by, or where methods.

# find by id
post = Post.find(1)

# find by title
post = Post.find_by(title: "My First Post")

# find all posts
posts = Post.all

Update

Updating an instance in Rails is as simple as setting a new value to the instance variable and then calling the save method.

# find the post
post = Post.find_by(title: "My First Post")

# update the title
post.title = "My Updated Post"
post.save

Delete

Deleting an instance from the database can be achieved using the destroy method.

# find the post
post = Post.find_by(title: "My Updated Post")

# delete the post
post.destroy

3. Code Examples

Let's put all these methods together into practical examples.

# Creating a new post
post = Post.new
post.title = "My First Post"
post.save
#=> true

# Reading the created post
post = Post.find_by(title: "My First Post")
#=> #<Post id: 1, title: "My First Post">

# Updating the post
post.title = "My Updated Post"
post.save
#=> true

# Deleting the post
post.destroy
#=> #<Post id: 1, title: "My Updated Post">

4. Summary

In this tutorial, we have covered how to perform CRUD operations in Rails, including creating, reading, updating, and deleting instances of a model. The next steps would be to learn how to create complex queries and relations between different models.

5. Practice Exercises

Here are some exercises to practice your new skills:

  1. Create a new model "User" with fields "name" and "email" and perform CRUD operations on it.

  2. Create a "Comment" model related to the "Post" model (a post has many comments), and create, read, update, and delete comments for a post.

  3. Create a "Profile" model that has one-to-one relation with the "User" model (a user has one profile), and create, read, update, and delete a profile for a user.

Remember, practice is key when it comes to programming. Keep practicing, and you'll get the hang of it in no time!