댓글 기능 추가하기 — 모델 연관관계 완전 정복

2025. 7. 22. 18:56·Ruby On Rails
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
'Ruby On Rails' 카테고리의 다른 글
  • Rails 앱 보안 점검 — CSRF, SQL Injection 막기
  • 메일 발송 기능 구현 — ActionMailer와 Gmail SMTP 연동하기
  • 관리자 페이지 만들기 — RailsAdmin vs ActiveAdmin
  • 파일 업로드 구현 — ActiveStorage와 Cloudinary 활용하기
코드를 걷는 사람
코드를 걷는 사람
devwanderer 님의 블로그 입니다.
  • 코드를 걷는 사람
    터미널 밖으로 나온 개발자
    코드를 걷는 사람
  • 전체
    오늘
    어제
    • 분류 전체보기
      • Flutter
        • Flutter 게시판 앱 만들기
        • Flutter 뉴스 앱 만들기
        • Flutter 메모 앱 만들기
        • Flutter 캘린더 앱 만들기
        • Flutter 날씨 앱 만들기
      • Next.js
      • Ruby On Rails
  • 블로그 메뉴

    • 홈
    • 태그
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    Nextjs
    코드를걷는사람
    ActiveRecord
    개발블로그
    모바일앱개발
    UI디자인
    Flutter
    Firebase
    다크모드
    fluttertips
    RubyOnRails
    flutter기초
    날씨앱
    openweather
    flutter게시판
    flutter개발
    flutterui
    캘린더앱
    UIUX
    뉴스앱
    table_calendar
    flutter상태관리
    flutter디자인
    백엔드개발
    감성앱
    정적사이트
    flutter앱개발
    메모앱
    rails보안
    북마크기능
  • 최근 댓글

  • 최근 글

  • 반응형
    250x250
  • hELLO· Designed By정상우.v4.10.3
코드를 걷는 사람
댓글 기능 추가하기 — 모델 연관관계 완전 정복
상단으로

티스토리툴바