빠른 참조

Rails ActiveRecord 모델 치트시트

Rails ActiveRecord 모델에 대한 종합 레퍼런스 가이드: 쿼리 스코프, 관계(Associations), 유효성 검사, 콜백, 변경 추적(Dirty Tracking) 및 집계.

· 게시일

ActiveRecord는 Rails MVC의 M(Model)을 나타내며, 비즈니스 로직, 데이터베이스 쿼리, 모델 관계 및 유효성 검사 규칙을 캡슐화합니다.

쿼리 메서드

# 기본 파인더
User.find(1)                  # 없으면 RecordNotFound 예외 발생
User.find_by(email: '[email protected]')# 없으면 nil 반환
User.first
User.last

# 조건 및 필터링
User.where(active: true)
User.where.not(role: 'banned')
User.where('age >= ?', 18)

# 정렬 및 슬라이싱
User.order(created_at: :desc).limit(10).offset(20)

# 스코프
class User < ApplicationRecord
  scope :active, -> { where(active: true) }
  scope :recent, -> { order(created_at: :desc) }
end

연관 관계 (Associations)

class Author < ApplicationRecord
  has_many :books, dependent: :destroy
  has_one :profile
  has_many :reviews, through: :books
end

class Book < ApplicationRecord
  belongs_to :author
  has_and_belongs_to_many :genres
end

유효성 검사 (Validations)

class User < ApplicationRecord
  validates :name, presence: true, length: { minimum: 2 }
  validates :email, presence: true, uniqueness: { case_sensitive: false }, format: { with: URI::MailTo::EMAIL_REGEXP }
  validates :age, numericality: { greater_than_or_equal_to: 13 }
  validates :role, inclusion: { in: %w[admin member guest] }
end

콜백 (Callbacks)

class Order < ApplicationRecord
  before_validation :normalize_currency
  before_create :generate_tracking_code
  after_create_commit :send_receipt_email

  private

  def normalize_currency
    self.currency = currency.upcase
  end
end

속성 변경 추적 (Dirty Tracking)

user = User.first
user.name = "New Name"

user.changed?        # => true
user.changed         # => ["name"]
user.changes         # => {"name" => ["Old Name", "New Name"]}
user.name_was        # => "Old Name"

집계 및 계산 (Aggregations)

Order.count
Order.sum(:total_amount)
Order.average(:rating)
Order.maximum(:price)
Order.minimum(:price)

참고 자료

관련 주제