자바스크립트를 허용해주세요.
[ 자바스크립트 활성화 방법 ]
from Mohon Aktifkan Javascript!
 

[Ruby on Rails] 4장 CRUD 기능 구현

728x90

1. 모델 생성

우선 기존 프로젝트에 게시판 기능을 추가한다고 가정해보겠습니다. 

rails generate model Post title:string content:text
rails db:migrate
  • rails generate model -> DB 테이블과 매핑되는 모델 + 마이그레이션 파일 생성
  • title -> 문자열 타입 컬럼, content -> 긴 텍스트 타입 컬럼 
  • rails db:migrate -> 마이그레이션 파일 실행, 실제 DB에 테이블 생성

✅ 2. RESTful 라우팅 등록

다음은 config/routes.rb에 resources:posts를 추가합니다.

Rails.application.routes.draw do
  resources :posts
end
  • resources :posts -> Rails가 CRUD를 위한 7개의 기본 라우팅 자동 생성 (index, show, new, create, edit,update, destroy)
  • rails routes로 확인 가능

✅ 3. 컨트롤러 생성

rails generate controller Posts

 

app/controllers/posts_controller.rb에 가서 아래와 같이 작성합니다.

class PostsController < ApplicationController
  before_action :set_post, only: [ :show, :edit, :update, :destroy ]

  # 전체 목록 (Read)
  def index
    @posts = Post.all
  end

  def show
  end

  # 새 글 작성 폼(Create)
  def new
    @post = Post.new
  end

  # 글 저장 (Create)
  def create
     @post = Post.new(post_params)
     if @post.save
        redirect_to @post, notice: "게시물이 성공적으로 생성되었습니다"
     else
      render :new
     end
  end

  # 수정 폼(Update)
  def edit
  end


  # 수정 저장(Update)
  def update
    if @post.update(post_params)
      redirect_to @post, notice: "게시물이 성공적으로 수정되었습니다."
    else
    render :edit
    end
  end

# 삭제
def destroy
   @post.destroy
   redirect_to post_url, notice: "게시물이 삭제되었습니다"
end

private

def set_post
   @post = Post.find(params[:id]) # id로 게시글 찾기
end

def post_params
   params.require(:post).permit(:title, :content)
end
end

 

 

📌 설명

  • before_action :set_post -> 중복되는 Post.find 로직을 묶어 재사용
  • post_params -> 폼에서 입력된 값 중 허용된 값만 받기(보안을 목적)

✅ 4. 뷰 생성 (ERB)

  • 목록 페이지 (index) - app/views/posts/index.html.erb
<h1>게시판</h1>
<%= link_to '새 글 작성', new_post_path %>

<ul>
  <% @posts.each do |post| %>
  <li>
    <%= link_to post.title, post %> | <%= link_to '수정', edit_post_path(post)
    %> | <%= button_to '삭제', post_path(post), method: :delete, data: {
    turbo_confirm: "정말 삭제하시겠습니까?" } %>
  </li>
  <% end %>
</ul>
  • 상세 페이지 (show) - app/views/posts/show.html.erb
<h1><%= @post.title %></h1>
<p><%= @post.content %></p>

<%= link_to '목록으로', posts_path %>
  • 글 작성 페이지 (new) - app/views/posts/new.html.erb
<h1>새글 작성</h1>
<%= render 'form', post: @post %>
  • 글 수정 페이지 (edit) - app/views/posts/edit.html.erb
<h1>글 수정</h1>
<%= render 'form', post: @post %>
  • 폼 부분(공통) - app/views/posts/_form.html.erb
<%= form_with(model: post, local: true) do |form| %>
<div>
  <%= form.label :title, "제목" %><br />
  <%= form.text_field :title %>
</div>

<div>
  <%= form.label :content, "내용" %><br />
  <%= form.text_area :content %>
</div>

<div><%= form.submit %></div>
<% end %>
  • form_with(model: post) -> 신규/수정 상황에 맞춰 자동으로 POST 또는 PATCH 요청을 보냄
  • _form.html.erb -> new/edit 둘 다에서 재사용함

✅ 5. 실행 & 확인

rails server
  • 브라우저에서 http://localhost:3000/posts 접속
  • 글 작성 -> 목록 확인 -> 수정 -> 삭제 흐름 확인

📌 정리

  • Model -> 데이터 구조화 DB 매핑
  • Controller -> 요청 처리, 데이터 가공
  • View -> 사용자에게 보여줄 UI
  • routes.rb -> URL과 컨트롤러 연결
  • Restful 구조로 URL 동작이 직관적( /posts/new, /posts/edit, /posts/1 )

 

 

GitHub - Koras02/rails-bloging: https://thinky.tistory.com/category/Back-End/Ruby

https://thinky.tistory.com/category/Back-End/Ruby. Contribute to Koras02/rails-bloging development by creating an account on GitHub.

github.com

 

728x90
LIST