728x90
반응형
게시판, 블로그, 커뮤니티… 어디서든 빠지지 않는 기능이 바로 댓글이죠.
이번 글에서는 Post와 Comment 사이의 관계를 설정하고, 댓글 작성/조회/삭제까지 구현하면서 Rails의 모델 연관관계를 완전히 이해해볼 거예요.
🧱 1. 모델 관계 설계: Post has_many Comments
Post가 여러 개의 Comment를 가지는 구조입니다.
$ bin/rails g model Comment body:text post:references
post:references는 post_id 컬럼을 자동으로 추가하고, 외래키 관계를 설정합니다.
# db/migrate/xxxxx_create_comments.rb
t.text :body
t.references :post, null: false, foreign_key: true
$ bin/rails db:migrate
🔗 2. 모델에 연관관계 선언하기
# app/models/post.rb
class Post < ApplicationRecord
has_many :comments, dependent: :destroy
end
# app/models/comment.rb
class Comment < ApplicationRecord
belongs_to :post
end
dependent: :destroy는 포스트가 삭제되면 해당 댓글들도 자동 삭제되게 합니다.
📝 3. 댓글 CRUD 구현하기
$ bin/rails g controller Comments
댓글 작성 폼 (posts/show.html.erb)
<%= form_with(model: [@post, Comment.new], local: true) do |f| %>
<p>
<%= f.label :body, "댓글 내용" %><br>
<%= f.text_area :body %>
</p>
<p>
<%= f.submit "댓글 달기" %>
</p>
<% end %>
댓글 리스트
<h3>댓글 목록</h3>
<% @post.comments.each do |comment| %>
<div class="comment">
<p><%= comment.body %></p>
<%= link_to "삭제", [@post, comment], method: :delete, data: { confirm: "정말 삭제할까요?" } %>
</div>
<% end %>
댓글 컨트롤러
# app/controllers/comments_controller.rb
class CommentsController < ApplicationController
before_action :set_post
def create
@comment = @post.comments.build(comment_params)
if @comment.save
redirect_to @post, notice: "댓글이 등록되었습니다."
else
redirect_to @post, alert: "댓글 등록 실패."
end
end
def destroy
@comment = @post.comments.find(params[:id])
@comment.destroy
redirect_to @post, notice: "댓글이 삭제되었습니다."
end
private
def set_post
@post = Post.find(params[:post_id])
end
def comment_params
params.require(:comment).permit(:body)
end
end
📌 4. 라우팅 설정
# config/routes.rb
resources :posts do
resources :comments, only: [:create, :destroy]
end
이렇게 설정하면 /posts/:post_id/comments로 중첩된 경로가 만들어져서 댓글이 포스트에 종속되도록 관리할 수 있어요.
🧠 has_many / belongs_to 요약
has_many는 반대쪽 모델의 여러 개 인스턴스를 참조belongs_to는 하나의 상위 모델에 속함dependent: :destroy옵션으로 부모 삭제 시 자식도 삭제- 중첩 리소스를 통해 라우팅과 컨트롤러 코드가 깔끔하게 구성됨
🎯 마치며
Rails는 관계형 데이터베이스와의 연결을 아주 자연스럽게 표현할 수 있는 문법을 가지고 있어요.
특히 댓글 기능을 만들면서 모델 간의 관계를 실감 나게 체험할 수 있죠.
이제 다른 기능도 이 관계를 기반으로 확장할 수 있을 거예요!
728x90
반응형
'Ruby On Rails' 카테고리의 다른 글
| Rails 앱 보안 점검 — CSRF, SQL Injection 막기 (2) | 2025.07.29 |
|---|---|
| 메일 발송 기능 구현 — ActionMailer와 Gmail SMTP 연동하기 (3) | 2025.07.24 |
| 관리자 페이지 만들기 — RailsAdmin vs ActiveAdmin (0) | 2025.07.17 |
| 파일 업로드 구현 — ActiveStorage와 Cloudinary 활용하기 (1) | 2025.07.15 |
| Devise로 로그인 기능 구현하기 — 인증은 쉽게, 안전하게 (0) | 2025.07.13 |
