💎
ActiveRecord
ORM — 객체로 데이터베이스를 조작
ActiveRecord는 Rails의 ORM(Object-Relational Mapping) 라이브러리로, 데이터베이스 테이블의 행(row)을 Ruby 객체로 매핑합니다.
기본 CRUD:
# Create
post = Post.create(title: '제목', content: '내용')
# Read
Post.find(1) # ID로 조회
Post.where(status: 'published') # 조건 조회
Post.order(created_at: :desc) # 정렬
# Update
post.update(title: '새 제목')
# Delete
post.destroy
쿼리 인터페이스:
where,order,limit,offset— 체이닝 가능includes,joins— 관계 테이블 조인group,having,count,sum— 집계find_by,find_or_create_by— 편의 메서드
콜백: before_save, after_create 등 라이프사이클 이벤트
유효성 검사: validates :title, presence: true 등
구조 다이어그램
Ruby (ActiveRecord)
Post.find(1)
Post.where(status: 'published')
Post.create(title: 'Hello')
post.update(title: 'New')
post.destroy
SQL (자동 변환)
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 (자동 매핑):
class Post
→
posts 테이블
post.title
→
title 컬럼
post.id
→
기본키 (자동)
핵심: <strong>Ruby 메서드가 SQL로 자동 변환</strong> — 객체 지향적으로 DB를 조작
핵심 포인트
1
모델 클래스 정의 — class Post < ApplicationRecord (ApplicationRecord < ActiveRecord::Base)
2
테이블 규약: Post 모델 → posts 테이블 자동 매핑
3
Post.new / Post.create로 새 레코드 생성
4
Post.find / Post.where로 레코드 조회 → SQL 자동 생성
5
post.update / post.save로 레코드 수정
6
post.destroy로 레코드 삭제
장점
- ✓ SQL 없이 Ruby로 DB 조작
- ✓ 쿼리 체이닝으로 직관적인 데이터 조회
- ✓ 마이그레이션으로 스키마 버전 관리
- ✓ DB 종류에 독립적 (SQLite, PostgreSQL, MySQL)
단점
- ✗ 복잡한 쿼리는 SQL이 더 효율적
- ✗ N+1 문제 주의 필요
- ✗ 대량 데이터 처리 시 메모리 문제
- ✗ 추상화로 인한 성능 오버헤드
사용 사례
모든 Rails 애플리케이션의 데이터 접근
CRUD 구현
복잡한 검색/필터/정렬
데이터 유효성 검사
관계(Association) 관리