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

[Ruby on Rails] 5장 폼 빌더, 모델 유효성 검사

728x90

✅ 1.  모델 생성

rails generate model Post title:string content:text
rails db:migrate
# app/models/post.rb - 모델 유효성 추가
class Post < ApplicationRecord
   # title은 반드시 존재해야 함, 최소 5글자
   validates :title, presence: true, length: { minimum: 5 }

   # content는 반드시 존재
   validates :content, presence: true
end

✅ 2. 컨트롤러 생성 

rails generate controller Posts
// app/controllers/posts_cotroller.rb
class PostsController < ApplicationController
  before_action :set_post, only: [ :show, :edit, :update, :destroy ]
  # 새 글 작성 폼(Create)
  def new
    @post = Post.new
  end

  def index
     @posts = Post.all
  end

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



  def show
    # @post = Post.find(params[:id])
  end
  def edit
    # @post는 before_action :set_post로 가져옴
  end

  def update
  if @post.update(post_params)
    redirect_to @post, notice: "게시글이 수정되었습니다."
  else
    render :edit
  end
  end

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


private

def set_post
    @post = Post.find(params[:id])
end

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

✅ 3.라우트 설정

// config/routes.rb
Rails.application.routes.draw do
  resources :posts, only: [ :index, :new, :create, :show, :edit, :update, :destroy ]
  root "posts#new"
end

✅ 4. view - 폼만들기

// app/views/posts/new.html.erb
<h1>새글 작성</h1>

<%= form_with model: @post, local: true do |form| %> <% if @post.errors.any? %>
<div style="color: red">
  <h2><%= pluralize(@post.errors.count, "error") %> 발생:</h2>
  <ul>
    <% @post.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
    <% end %>
  </ul>
</div>
<% end %>

<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 %>
// app/views/posts/show.html.erb - 상세 페이지 보기
<h1><%= @post.title %></h1>
<p><%= @post.content %></p>

<%= link_to '목록으로', posts_path %>

✅ 5. 테스트 

rails s
  • 브라우저에서 http://localhost:3000 접속
  • 제목과 내용 입력후 제출
  • 유효성 검사 실패 시 오류 메시지 출력, 성공 시 게시글 상세 페이지 이동 

 

 

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