0
0
Ruby on Railsframework~5 mins

CRUD operations through models in Ruby on Rails

Choose your learning style9 modes available
Introduction

CRUD operations let you create, read, update, and delete data easily using models. Models connect your app to the database in a simple way.

When you want to add new records to your database, like adding a new user.
When you need to show data from the database, like listing all products.
When you want to change existing data, like updating a user's email.
When you want to remove data, like deleting a comment.
When you want to keep your code clean by using Rails models to handle data.
Syntax
Ruby on Rails
# Create
Model.create(attributes)

# Read
Model.find(id)
Model.where(condition)
Model.all

# Update
record = Model.find(id)
record.update(attributes)

# Delete
record = Model.find(id)
record.destroy

Use create to add new records quickly.

find raises an error if no record is found; where returns an empty collection if none match.

Examples
This creates a new user with name and email.
Ruby on Rails
User.create(name: "Alice", email: "alice@example.com")
This finds the user with ID 1.
Ruby on Rails
User.find(1)
This gets all users who are active.
Ruby on Rails
User.where(active: true)
This finds user 1 and updates their email.
Ruby on Rails
user = User.find(1)
user.update(email: "newemail@example.com")
Sample Program

This example shows all CRUD steps: create a user, read it, update the name, then delete it. Finally, it checks if the user still exists.

Ruby on Rails
class User < ApplicationRecord
end

# Create a user
user = User.create(name: "Bob", email: "bob@example.com")

# Read the user
found_user = User.find(user.id)

# Update the user
found_user.update(name: "Bobby")

# Delete the user
found_user.destroy

puts User.exists?(user.id)
OutputSuccess
Important Notes

Always handle exceptions when using find to avoid app crashes if record is missing.

Use update to change only the fields you want.

destroy removes the record from the database permanently.

Summary

CRUD stands for Create, Read, Update, Delete.

Rails models make CRUD easy and clean.

Use model methods like create, find, update, and destroy to manage data.