Part 4: CRUD Operations

In this part, you'll learn how to create, read, update, and delete records in your blog engine. You'll also explore querying patterns, bulk operations, and best practices for working with data.

What You'll Learn

  • Creating records (single and bulk)

  • Reading and querying records

  • Updating records

  • Deleting records

  • Using query scopes

  • Aggregation and counting

Prerequisites

Create Operations

Creating a Single Record

There are several ways to create records:

# Method 1: new + save
user = User.new(username: "john", email: "john@example.com")
if user.save
  puts "User created with ID: #{user.id}"
else
  puts "Failed to create user"
end

# Method 2: create! (raises on failure)
user = User.create!(
  username: "jane",
  email: "jane@example.com",
  first_name: "Jane"
)

# Method 3: create (returns the record, check persisted?)
user = User.create(username: "bob", email: "bob@example.com")
if user.persisted?
  puts "User created"
end

Creating with Relationships

Creating Multiple Records

Read Operations

Finding by ID

Finding by Attributes

Querying Multiple Records

Complex Queries

Querying Through Relationships

Pagination

Update Operations

Updating a Single Record

Incrementing Values

Bulk Updates

Delete Operations

Deleting a Single Record

Deleting with Conditions

Cascading Deletes

Remember our foreign key setup? Deleting a user cascades to their posts, which cascade to comments:

Aggregations

Counting

Sum, Average, Min, Max

Grouping and Statistics

Batch Processing

For large datasets, process records in batches:

Practical Examples

Blog Dashboard Data

Recent Activity Feed

Search Posts

Summary

In this part, you learned:

  1. Create: new + save, create, and create!

  2. Read: find, find_by, where, order, limit

  3. Update: attribute assignment + save, update!, bulk updates

  4. Delete: delete!, destroy!, bulk deletes

  5. Aggregate: count, sum, avg, min, max

  6. Batch: find_each for large datasets

Next Steps

In Part 5: Adding Features, you'll add validations, callbacks, and performance monitoring to complete your blog engine.


Tutorial Navigation:

Last updated

Was this helpful?