๐Ÿ’Ž

ActiveRecord

ORM โ€” manipulate databases with objects

ActiveRecord is Rails' ORM (Object-Relational Mapping) library that maps database table rows to Ruby objects.

Basic CRUD:

# Create
post = Post.create(title: 'Title', content: 'Content')

# Read
Post.find(1)              # Find by ID
Post.where(status: 'published')  # Conditional query
Post.order(created_at: :desc)    # Sort

# Update
post.update(title: 'New Title')

# Delete
post.destroy

Query Interface:

  • where, order, limit, offset โ€” chainable

  • includes, joins โ€” join related tables

  • group, having, count, sum โ€” aggregation

  • find_by, find_or_create_by โ€” convenience methods

Callbacks: before_save, after_create, etc. for lifecycle events
Validations: validates :title, presence: true, etc.

Architecture Diagram

Ruby (ActiveRecord)
Post.find(1)
Post.where(status: 'published')
Post.create(title: 'Hello')
post.update(title: 'New')
post.destroy
SQL (Auto-converted)
SELECT * FROM posts WHERE id = 1
SELECT * FROM posts WHERE status = 'published'
INSERT INTO posts (title) VALUES ('Hello')
UPDATE posts SET title = 'New' WHERE id = 1
DELETE FROM posts WHERE id = 1
Convention (Auto-mapping):
class Post posts table
post.title title column
post.id Primary key (auto)
Key point: <strong>Ruby methods are auto-converted to SQL</strong> โ€” manipulate DB in an object-oriented way

Key Points

1

Define model class โ€” class Post < ApplicationRecord (ApplicationRecord < ActiveRecord::Base)

2

Table convention: Post model โ†’ posts table auto-mapped

3

Create new records with Post.new / Post.create

4

Query records with Post.find / Post.where โ†’ SQL auto-generated

5

Update records with post.update / post.save

6

Delete records with post.destroy

Pros

  • Manipulate DB with Ruby without SQL
  • Intuitive data queries via query chaining
  • Schema version control via migrations
  • DB-agnostic (SQLite, PostgreSQL, MySQL)

Cons

  • Complex queries are more efficient in raw SQL
  • N+1 problem requires attention
  • Memory issues with large data processing
  • Performance overhead from abstraction

Use Cases

Data access in all Rails applications CRUD implementation Complex search/filter/sort Data validation Association management