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โ chainableincludes,joinsโ join related tablesgroup,having,count,sumโ aggregationfind_by,find_or_create_byโ convenience methods
Callbacks: before_save, after_create, etc. for lifecycle events
Validations: validates :title, presence: true, etc.
Architecture Diagram
class Post
→
posts table
post.title
→
title column
post.id
→
Primary key (auto)
Key Points
Define model class โ class Post < ApplicationRecord (ApplicationRecord < ActiveRecord::Base)
Table convention: Post model โ posts table auto-mapped
Create new records with Post.new / Post.create
Query records with Post.find / Post.where โ SQL auto-generated
Update records with post.update / post.save
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