[Ruby on Rails] 1장. 라우팅과 컨트롤러

1. 라우팅 (Routing)

라우팅은 URL 요청을 특정 컨트롤러의 액션에 매핑하는 역할로, Rails에서 config/routes.rb 파일에 라우팅을 직접 설정할 수 있습니다. 먼저 기본적인 라우팅 설정은 다음과 같습니다.

Rails.application.routes.draw do
  resources :articles
  get "articles", to: "articles#index"   # 모든 기사 목록
  get "articles/new", to: "articles#new" # 새 기사 작성 폼
  post "articles", to: "articles#create"  # 새 기사 생성
  get "articles/:id", to: "articles#show" # 특정 기사 보기
  get "articles/:id/edit", to: "articles#edit" # 기사 수정 폼
  patch "articles/:id", to: "articles#update" # 기사 업데이트
  delete "articles/:id", to: "articles#destroy" # 기사 삭제
end

2. 컨트롤러(Controller)

컨트롤러는 요청을 처리하고, 비즈니스 로직을 수행하며, 뷰를 렌더링하는 역할로, app/controllers 디렉토리에 위치합니다. 컨트롤러를 생성하려면 다음 명령어를 사용할 수 있습니다.

rails generate controller Articles

 

이 명령어는 ArticlesController라는 파일과 기본적인 액션을 포함하는 파일을 생성하는 명령어 입니다.


3. 컨트롤러 생성 및 액션 정의

컨트롤러에서 액션을 정의하는 예시는 다음과 같습니다.

class ArticlesController < ApplicationController
  def index
    @articles = Article.all
  end

  def show
    @articles = Article.find(params[:id])
  end

  def new
    @articles = Article.new
  end

  def create
    @articles = Article.new(article_params)
    if @articles.save
      redirect_to @article
    end
  end

  def edit
    @article = Article.find(params[:id])
  end

  def update
    @article = Article.find(params[:id])
    if @article.update(article_params)
      redirect_to @article
    else
      render :edit
    end
  end

  def destroy
    @article = Article.find(params[:id])
    @article.destroy
    redirect_to articles_path
  end

  private

  def article_params
    params.require(:article).permit(:title, :body)
  end
end

4. 모델 생성 

이제 articles를 테스트하기 위해 Article 모델을 생성해야합니다. 아래 명령어로 모델을 생성해줍니다.

rails generate model Article title:string body:text

 

모델 생성후 데이터베이스에 articles 테이블을 추가하기 위해 마이그레이션을 실행합니다.

rails db:migrate

 

모델 파일이 app/models/article.rb에 생성되었는지 확인합니다. 그 다음 index 액션을 위한 뷰 파일을 생성합니다. app/views/articles 디렉토리에 index.html.erb 파일을 생성합니다. 그 다음 아래와 같은 내용을 추가합니다.

<h1>Articles</h1>

<table>
  <thead>
    <tr>
      <th>Title</th>
      <th>Body</th>
      <th>Actions</th>
    </tr>
  </thead>
  <tbody>
    <% @articles.each do |article| %>
      <tr>
        <td><%= article.title %></td>
        <td><%= article.body %></td>
        <td>
          <%= link_to 'Show', article_path(article) %>
          <%= link_to 'Edit', edit_article_path(article) %>
          <%= link_to 'Destroy', article_path(article), method: :delete, data: { confirm: 'Are you sure?' } %>
        </td>
      </tr>
    <% end %>
  </tbody>
</table>

<%= link_to 'New Article', new_article_path %>

 

이제 cmd에 rails console을 실행시켜 다음 명령어를 입력해 0이 반환되면 데이터를 추가해줍니다.

rails console

Article.count # 데이터가 0일시 데이터 추가해야함

5. 데이터 추가

Rails 콘솔을 통해 직접 데이터를 추가할 수 있습니다. 먼저 rails console을 실행시키고 다음 명령어를 입력해 Article 데이터를 추가해줍니다.

Article.create(title: '첫 번째 기사', body: '이것은 첫 번째 기사입니다.')
Article.create(title: '두 번째 기사', body: '이것은 두 번째 기사입니다.')

 

이제 다음 명령어로 데이터가 제데로 추가되었는지 확입해봅니다.

Article.all

6. 뷰 파일 검토

app/views/articles 디렉토리에 show.html.erb 파일을 생성하고 다음과 같은 내용을 추가합니다. 먼저 articles_controller.rb에 show 예외처리를 해줍니다.

 def show
    @article = Article.find(params[:id])
  rescue ActiveRecord::RecordNotFound
    redirect_to articles_path, alert: "Article not found."
  end

 

다음 show.html.erb 파일을 생성해 아래와 같은 코드를 입력합니다.

<h1><%= @article.title %></h1>
<p><%= @article.body %></p>

<%= link_to 'Edit', edit_article_path(@article) %>
<%= link_to 'Back', articles_path %>

7. 수정, 새로만들기

이제 글을 수정하고 새로 만들기를 구현하기 위해 app/controllers/articles_controller.rb 파일에 다음과 같은 내용을 추가해줍니다.

class ArticlesController < ApplicationController
  def index
    @articles = Article.all
  end

  def show
    @article = Article.find(params[:id])
  rescue ActiveRecord::RecordNotFound
    redirect_to articles_path, alert: "Article not found."
  end

  def new
    @article = Article.new
    puts @article.inspect # 여기서 @article의 상태를 출력합니다.
  end

  def create
    @article = Article.new(article_params)
    if @article.save
      redirect_to @article, notice: "Article was successfully created."
    else
      render :new
    end
  end

  def edit
    @article = Article.find(params[:id])
  end

  def update
    @article = Article.find(params[:id])
    if @article.update(article_params)
      redirect_to @article, notice: "Article was successfully updated."
    else
      render :edit
    end
  end

  def destroy
    @article = Article.find(params[:id])
    @article.destroy
    redirect_to articles_path, notice: "Article was successfully deleted."
  end

  private

  def article_params
    params.require(:article).permit(:title, :body)
  end
end

 

먼저 app/vies/articles/new.html.erb 파일을 새로 만들어 다음과 같은 내용을 추가합니다.

<h1>New Articles Write</h1>

<%= form_with model: @article, local: true do |form| %>
  <% if @article.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@article.errors.count, "error") %> prohibited this article from being saved:</h2>
      <ul>
        <% @article.errors.full_messages.each do |message| %>
          <li><%= message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= form.label :title %>
    <%= form.text_field :title %>
  </div>

  <div class="field">
    <%= form.label :body %>
    <%= form.text_area :body %>
  </div>

  <div class="actions">
    <%= form.submit 'Create Article' %>
  </div>
<% end %>

<%= link_to 'Back', articles_path %>

 

다음 edit.html.erb도 생성해 다음과 같은 내용을 추가합니다.

<h1>기사 수정</h1>

<%= form_with model: @article, local: true do |form| %>
  <% if @article.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@article.errors.count, "error") %> prohibited this article from being saved:</h2>
      <ul>
        <% @article.errors.full_messages.each do |message| %>
          <li><%= message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= form.label :title %>
    <%= form.text_field :title %>
  </div>

  <div class="field">
    <%= form.label :body %>
    <%= form.text_area :body %>
  </div>

  <div class="actions">
    <%= form.submit 'Update Article' %>
  </div>
<% end %>

<%= link_to 'Back', articles_path %>

 

이제 config/routes.rb 파일이 다음과 같이 설정되어 있는지 확인합니다.

Rails.application.routes.draw do
  resources :articles
end

 

 

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

 

LIST

'Back-End > Ruby' 카테고리의 다른 글

[Ruby on Rails] 2장. 모델과 데이터베이스  (0) 2025.04.03
[Ruby on Rails] Ruby on Rails란?  (0) 2025.03.25
[Ruby] 9장(완) 루비 고급 주제  (0) 2025.03.15
[Ruby] 8장 예외처리  (0) 2025.03.12
[Ruby] 7장 파일 입출력  (0) 2025.03.08