728x90
반응형
Rails에서 데이터베이스와 소통하는 방식은 ActiveRecord를 통해 이루어집니다. ActiveRecord는 ORM(Object-Relational Mapping) 역할을 하며, 데이터베이스의 테이블과 Ruby 객체를 연결시켜줍니다. 이 글에서는 Rails의 핵심 기능인 CRUD (Create, Read, Update, Delete)를 ActiveRecord를 통해 어떻게 다루는지 정리해보겠습니다.
📘 모델 생성
$ bin/rails generate model Post title:string content:text
$ bin/rails db:migrate
위 명령어로 posts
테이블이 생성되고, Post
모델이 생성됩니다. 이제 이 Post 모델로 DB 조작이 가능해집니다.
🆕 Create (데이터 생성)
post = Post.new(title: "Hello", content: "This is my first post!")
post.save
혹은 더 간단히:
Post.create(title: "Hello", content: "This is my first post!")
🔍 Read (데이터 조회)
Post.all
— 모든 레코드 조회Post.find(1)
— id가 1인 레코드 조회Post.find_by(title: "Hello")
— 조건으로 조회Post.where("title LIKE ?", "%Rails%")
— SQL처럼 조회
Post.order(created_at: :desc).limit(5)
최근 5개의 포스트만 조회하는 예시입니다.
✏️ Update (데이터 수정)
post = Post.find(1)
post.title = "Updated Title"
post.save
또는 한 줄로:
post.update(title: "Updated Title")
🗑️ Delete (데이터 삭제)
post = Post.find(1)
post.destroy
또는:
Post.destroy(1)
💡 유용한 ActiveRecord 메서드
exists?
— 특정 조건의 레코드 존재 여부 확인count
— 전체 개수first / last
— 첫 번째 또는 마지막 레코드pluck(:title)
— 특정 컬럼만 배열로 추출
Post.where(published: true).pluck(:title)
🎯 마치며
ActiveRecord를 이해하는 것은 Rails를 제대로 활용하는 첫걸음입니다. SQL을 직접 작성하지 않아도 Ruby 문법으로 직관적인 데이터 조작이 가능하다는 점에서 매우 강력하죠. 다음 글에서는 모델 간의 관계 (has_many, belongs_to)를 다뤄보며 데이터의 연결 구조를 알아볼게요.
728x90
반응형
'Ruby On Rails' 카테고리의 다른 글
마이그레이션과 스키마 변화 — 안전하게 DB 구조 바꾸기 (1) | 2025.07.09 |
---|---|
Rails에서의 MVC 구조 진짜 제대로 파보기 (2) | 2025.07.08 |
Rails의 라우팅 시스템 — config/routes.rb 제대로 이해하기 (0) | 2025.07.06 |
첫 번째 Rails 앱 만들기 — Blog 프로젝트로 배우는 MVC (0) | 2025.07.05 |
RoR 개발환경 구축 — macOS, Windows에서 시작하기 (1) | 2025.07.04 |