Uploaded by 최현준

rails basic

advertisement
루비온레일즈 8: 몇 시간 만에 첫 웹 서비스 배포하기
안녕하세요! 20년 차 개발자 제임스입니다
20년 스타트업 개발 전문가
350+ 프로젝트 성공, 85억 매출 달성 노하우
10시간 안에 웹 서비스 배포 목표
문의: james@insomenia.com
1
왜 루비온레일즈를 배워야 할까요?
유명 서비스들이 선택한 검증된 기술
빠른 개발 속도, 높은 생산성
풀스택 프레임워크: 웹 개발 All-in-one
강력한 기본 기능 & 풍부한 Gem 생태계
쉬운 유지보수
2
풀스택 vs 분리?
구분 루비온레일즈 (풀스택) 프론트/백엔드 분리
개발 속도
매우 빠름
빠름
복잡도
낮음
높음
생산성
매우 높음
높음
유지보수 쉬움
중간
초기 설정 간단
복잡
학습 곡선 쉬움
어려움
배포
쉬움
중간
SEO
유리
불리
3
10분 시연: 레일즈 마법
터미널 명령어
rails new myblog -c tailwind
cd myblog
rails generate scaffold Post title:string content:text
rails db:migrate
./bin/dev
브라우저 접속: http://localhost:3000/posts
5분 만에 게시글 CRUD 완성!
4
무엇을 배울 수 있나요?
루비온레일즈 8 최신 기능
Tailwind CSS 스타일링
MVC 패턴 & RESTful API 설계
Hotwire Modern 웹 UI
Kamal 배포
개인 프로젝트 배포 가능!
웹 서비스 개발 & 배포, 이제 당신도 할 수 있습니다!
5
강의 로드맵 1. 시작하기: Rails 개발 환경 설정
2. 프로젝트 구조: MVC 패턴 & 파일 구조
3. 모델 & DB: Active Record, 마이그레이션, CRUD
4. 뷰 & ERB: HTML, ERB, 레이아웃, Tailwind CSS
5. 컨트롤러 & 라우팅: 요청 처리, RESTful API
6. Scaffold: 자동 CRUD 기능 생성
7. Hotwire: Modern 웹 UI 개발
8. Gem 활용: 유용한 Gem 소개 & 사용법
9. 배포: Kamal
10. 마무리: Rails 강점 & 학습 가이드
6
챕터 1: 시작하기
1.1 루비온레일즈란? - 풀스택 웹 프레임워크 (Ruby 기반)
MVC 패턴: 체계적인 코드 구조
설정보다 관례: 빠른 개발, 코드 일관성
DRY: 코드 중복 최소화, 생산성 향상
7
1.2 개발 환경 준비 필수 프로그램: Ruby, Rails
1. Ruby: rbenv (버전 관리자) 추천
설치
기준
# rbenv
(macOS
)
brew install rbenv
rbenv init
#
(eval "$(rbenv init -)")
source ~/.zshrc # or ~/.bashrc
rbenv install 3.3.0
rbenv local 3.3.0
ruby -v
쉘 설정
8
1.2 개발 환경 준비 (계속)```bash
rails new myapp -c tailwind
cd myapp
rails server
프로젝트 생성
- `myapp`
, Tailwind CSS
- `http://localhost:3000`
접속 확인
설정
**Yay! You’re on Rails!**
---
챕터 2: 프로젝트 구조
### 2.1 MVC 패턴
- **Model**: 데이터 & 비즈니스 로직 (Active Record)
- **View**: 사용자 인터페이스 (UI)
- **Controller**: Model & View 연결 (중재자)
##
---
패턴 (계속)**MVC 장점**
- 코드 구조화, 유지보수 용이
- 재사용성, 협업 효율 증대
### 2.1 MVC
---
파일 구조
### 2.2
```
myapp/
├── app/
│
├── controllers/
│
├── models/
9
2.2 파일 구조 (계속)주요 폴더
: MVC 파일 위치
controllers/ , models/ , views/
config/ : 환경 설정 (routes.rb, database.yml)
db/ : 데이터베이스 (migrate/)
public/ : 정적 파일
app/
10
2.3 config/routes.rb - URL 라우팅 설정: URL → Controller#Action 연결
config/routes.rb
파일
Rails.application.routes.draw do
get "up" => "rails/health#show"
# root "articles#index"
end
: /up 요청 → rails/health#show
root ... : / 요청 → articles#index (주석처리)
get "up" => ...
11
2.3 config/routes.rb (계속)라우팅 예시
Rails.application.routes.draw do
get '/posts', to: 'posts#index'
get '/posts/:id', to: 'posts#show'
# ...
end
→ posts#index
/posts/:id → posts#show (id 파라미터)
RESTful 라우팅 (뒤에서 설명)
/posts
12
챕터 3: 모델 & DB
3.1 모델 (Model) - 데이터 & 비즈니스 로직 담당
Active Record: Rails ORM
Ruby 객체 DB 테이블 매핑
SQL 없이 DB 조작
모델 생성 예시: Post
rails generate model Post title:string content:text
13
3.1 모델 (Model) (계속) app/models/post.rb 확인
class Post < ApplicationRecord
end
상속 → Active Record 기능
단수 모델명, 파스칼 클래스명 (Post)
db/migrate 폴더에 마이그레이션 파일 생성 확인
ApplicationRecord
14
3.2 마이그레이션 (Migration) - DB 스키마 변경 이력 관리
마이그레이션 파일: Ruby 코드 정의
rails db:migrate : 마이그레이션 실행
db/migrate/xxxxxxxxxxxxxx_create_posts.rb
class CreatePosts < ActiveRecord::Migration[7.1]
def change
create_table :posts do |t|
t.string :title
t.text :content
t.timestamps
end
end
end
15
3.2 마이그레이션 (Migration) (계속)- create_table :posts : posts 테이블
생성
: title 컬럼 (string)
t.text :content : content 컬럼 (text)
t.timestamps : created_at, updated_at 자동 생성
t.string :title
마이그레이션 실행
rails db:migrate
db/schema.rb
업데이트 확인
16
3.3 CRUD & Active Record - CRUD: DB 기본 조작 (생성, 조회, 수정, 삭제)
Active Record 메소드: SQL 없이 Ruby CRUD
Create (생성)
제목
내용')
post = Post.new(title: '
', content: '
post.save
#
Post.create(title: '
', content: '
')
또는
제목
내용
17
3.3 CRUD & Active Record (계속)Read (조회)
모든
posts = Post.all #
Post
post = Post.find(1) # ID
posts = Post.where(title: '
first_post = Post.first #
# ...
로 조회
제목') # 조건 조회
첫번째 Post
18
3.3 CRUD & Active Record (계속)Update (수정)
post = Post.find(1)
post.title = '
'
post.save
새 제목
Delete (삭제)
post = Post.find(2)
post.destroy
#
Post.destroy_all (
또는
주의!)
19
3.3 CRUD & Active Record (계속)Rails Console: Active Record 테스트
rails console
제목', content: '내용')
Post.create(title: '
Post.all
Post.last.destroy
20
챕터 4: 뷰 & ERB
4.1 뷰 (View) - 웹 페이지 UI (HTML, CSS, JavaScript)
폴더, .html.erb 확장자
ERB: HTML + Ruby 코드
app/views/posts/index.html.erb 예시
app/views
게시글 목록
<h1>
</h1>
<table>...</table>
<br>
<%= link_to '
새 게시글', new_post_path %>
21
4.1 뷰 (View) (계속)- <h1> : HTML 제목
<table>
: HTML 테이블
<% @posts.each do |post| %>
: Ruby 반복문, @posts 변수 사용
: Ruby 출력, 게시글 제목
<%= link_to ... %> : Rails 뷰 헬퍼, HTML 링크 생성
<%= post.title %>
22
4.2 레이아웃 (Layout) - 공통 레이아웃 (header, footer 등)
app/views/layouts/application.html.erb
yield
: 뷰 파일 내용 삽입 위치
app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
<head>...</head>
<body class="bg-gray-100">
<header>...</header>
<main>
<%= yield %>
</main>
</body>
</html>
23
4.2 레이아웃 (Layout) (계속)- <body> , <header> , <main> HTML 구조
Tailwind CSS 클래스 적용 예시
<%= yield %> : 뷰 내용 삽입
Tailwind CSS: stylesheet_link_tag "tailwind"
24
4.3 Tailwind CSS 스타일링 - Utility-First CSS 프레임워크
: 설정 파일
application.tailwind.css : 기본 스타일
Tailwind CSS 예시 (버튼)
tailwind.config.js
버튼', path, class: 'bg-green-500 text-white ...' %>
<%= link_to '
: utility 클래스 조합
bg-green-500 , text-white , ...
class="..."
25
4.3 Tailwind CSS 스타일링 (계속)Tailwind CSS 장점
빠른 스타일링, 일관성 유지
반응형 디자인, 커스터마이징 용이
app/views/posts/index.html.erb
Tailwind 적용 예시 (코드 참고)
26
Ruby 기초 문법 배우기 ### 1. 변수와 데이터 타입
변수 선언 타입 선언 불필요)
문자열
정수
실수
불리언
# 문자열 보간
puts "#{name}님의 나이는 #{age}세입니다."
#
(
name = "James"
#
age = 30
#
height = 175.5
#
is_developer = true #
27
2. 배열과 해시
배열
#
fruits = ["
fruits << "
fruits[0]
사과", "바나나", "오렌지"]
망고" # 배열에 추가
# => "사과"
# 해시 (키-값 쌍)
person = {
name: "James",
age: 30,
skills: ["Ruby", "Rails"]
}
puts person[:name] # => "James"
28
3. 제어문
문
# if
if age >= 20
puts "
else
puts "
end
성인입니다"
미성년자입니다"
반복문
# each
fruits.each do |fruit|
puts "#{fruit}
end
는 맛있어요!"
29
4. 메서드 정의
메서드 정의
안녕하세요
#
def greet(name)
"
, #{name} !"
end
메서드 호출
#
puts greet("James")
님
안녕하세요, James님!"
# 물음표로 끝나는 메서드 (참/거짓 반환)
# => "
def adult?(age)
age >= 20
end
30
5. 클래스와 객체
클래스 정의
#
class Person
attr_accessor :name, :age
#
게터/세터 자동 생성
def initialize(name, age)
@name = name #
@age = age
end
인스턴스 변수
def introduce
"
#{@name}
end
end
저는
이고, #{@age}세입니다."
객체 생성과 사용
#
james = Person.new("James", 30)
puts james.introduce
31
6. Ruby의 특별한 기능들
블록
#
3.times { puts "
안녕하세요!" }
# 심볼 (문자열보다 가볍고 빠름)
status = :active
메서드 체이닝
#
names = ["james", "john", "jane"]
puts names.map(&:upcase).join(", ")
안전 연산자
# nil
user&.name
가 nil이면 에러 대신 nil 반환
# user
32
챕터 5: 컨트롤러 & 라우팅
5.1 컨트롤러 (Controller) - 요청 처리, Model & View 연결
app/controllers/
폴더
액션: 요청 처리 메소드 (index, show, ...)
인스턴스 변수: 뷰에 데이터 전달 ( @변수 )
컨트롤러 생성 예시: PostsController
rails generate controller Posts index show new create edit update destroy
33
5.1 컨트롤러 (Controller) (계
속) app/controllers/posts_controller.rb
class PostsController < ApplicationController
def index # @posts
end
def show # @post
end
def new # @post new
end
def create # @post create, redirect or render
end
def edit # @post
end
def update # @post update, redirect or render
end
def destroy # @post destroy, redirect
end
private def post_params # Strong Parameters
end
end
설정
설정
설정
34
5.1 컨트롤러 (Controller) (계속)- CRUD 액션 (index, show, ...)
인스턴스 변수 ( @posts , @post ) 뷰 전달
params[:id] : URL 파라미터 접근
redirect_to , render : 페이지 이동 & 뷰 렌더링
private post_params : Strong Parameters (보안)
35
5.2 RESTful API & 라우팅 - RESTful API: 웹 API 설계 스타일
-
자원 중심, HTTP 메소드 활용
Rails 라우팅: RESTful API 쉽게 구현
36
RESTful 라우팅 규칙
Method
URL
Action 역할
/posts
GET
index 목록 조회
/posts/new
GET
new 작성 폼
/posts
POST
create 생성
/posts/:id
GET
show 상세 조회
/posts/:id/edit
GET
edit 수정 폼
PUT/PATCH /posts/:id
update 수정
DELETE /posts/:id
destroy 삭제
37
5.2 RESTful API & 라우팅 (계속) config/routes.rb 수정
Rails.application.routes.draw do
resources :posts
# ...
end
resources :posts
rails routes
: RESTful 라우팅 자동 설정
명령어 확인
posts GET /posts ... posts#index
...
라우팅 헬퍼: URL 생성 편리 ( posts_path , post_path(post) )
38
챕터 6: Scaffold 심층 분석
6.1 Scaffold 란?
CRUD 기능 자동 생성: Model, View, Controller, Route, Migration
빠른 개발, 학습 도구
Scaffold 명령어 복습
rails generate scaffold Post title:string content:text
Post
모델 Scaffold 생성
title:string content:text
: 속성 정의
39
6.1 Scaffold 란? (계속)Scaffold 결과물
Model: app/models/post.rb
Controller: app/controllers/posts_controller.rb
Views: app/views/posts/ (index, show, ...)
Route: config/routes.rb (resources :posts)
Migration: db/migrate/...create_posts.rb
생성 코드 분석: 이전 챕터 내용 복습
40
6.2 Scaffold View 분석 - app/views/posts/ : index, show, new, edit,
_form.html.erb
_form.html.erb
분석: 폼 코드 분리, 재사용
<%= form_with(model: post) do |form| %>
<% if post.errors.any? %> ... <% end %>
<div>
<%= form.label :title %>
<%= form.text_field :title %>
</div>
<div>
<%= form.label :content %>
<%= form.text_area :content %>
</div>
<div>
<%= form.submit %>
</div>
<% end %>
41
6.2 Scaffold View 분석 (계속)- <%= form_with(model: post) do
|form| %> : 폼 헬퍼, 모델 연결
- `model: post`: `@post`
- `form`:
폼 빌더 객체
인스턴스 변수
: 에러 출력
<%= form.label :title %> : label 태그
<%= form.text_field :title %> : text field
...
<% if post.errors.any? %>
42
6.3 Scaffold Controller 분석
분석
app/controllers/posts_controller.rb
CRUD 액션 (챕터 5 복습)
before_action :set_post, only: [...]
set_post
메소드: 코드 효율 & 가독성
: before action 등록
class PostsController < ApplicationController
before_action :set_post, only: %i[...]
# ... actions ...
private
def set_post
@post = Post.find(params[:id])
end
# ...
end
43
6.3 Scaffold Controller 분석 (계속)- before_action : 특정 액션 전
set_post
실행
: private 메소드 정의
@post = Post.find(params[:id]) : @post 설정 (params[:id] 사용)
Scaffold 활용: 기본 기능 생성 후 수정 & 확장
private def set_post
44
6.4 Scaffold View 분석 (계속) app/views/posts/index.html.erb 분석
게시글 목록
<h1>
</h1>
<table>...</table>
<br>
<%= link_to '
새 게시글', new_post_path %>
45
6.5 Scaffold 활용 팁 Scaffold 활용 방법
기본 CRUD 기능 빠르게 생성
필요한 부분만 수정
다른 모델에 적용
46
챕터 7: Hotwire로 모던 웹 UI 개발
47
7.1 Hotwire 소개
Hotwire = Turbo + Stimulus
서버 중심 아키텍처: JavaScript 최소화
실시간 UI: SPA 수준의 반응성
프로그레시브 향상: 기본 동작 보장
48
7.2 Turbo 핵심 기능
1. Turbo Drive
페이지 전환 가속화
전체 페이지 새로고침 없음
기본적으로 활성화되어 있음
# app/views/posts/index.html.erb
<div id="posts">
<h1>
</h1>
<%= link_to "
", new_post_path %> <%#
게시글 목록
새 게시글
<% @posts.each do |post| %>
<%= link_to post_path(post) do %>
<h2><%= post.title %></h2>
<% end %>
<% end %>
</div>
자동으로 Turbo Drive 적용 %>
49
2. Turbo Frames
페이지 일부분만 업데이트
# app/views/posts/index.html.erb
<div class="posts-container">
<h1>
</h1>
게시글 목록
<%= turbo_frame_tag "new_post" do %>
<%= link_to "
", new_post_path %>
<% end %>
새 게시글
<%= turbo_frame_tag "posts" do %>
<%= render @posts %>
<% end %>
</div>
50
# app/views/posts/new.html.erb
<%= turbo_frame_tag "new_post" do %>
<%= form_with(model: @post) do |f| %>
<%= f.text_field :title %>
<%= f.text_area :content %>
<%= f.submit %>
<% end %>
<% end %>
51
3. Turbo Streams
실시간 업데이트
# posts_controller.rb
def create
@post = Post.create(post_params)
respond_to do |format|
format.turbo_stream
end
end
# create.turbo_stream.erb
<%= turbo_stream.append "posts" do %>
<%= render @post %>
<% end %>
52
7.3 Stimulus로 JavaScript 관리
1. 컨트롤러 정의
// toggle_controller.js
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = [ "content" ]
}
toggle() {
this.contentTarget.classList.toggle("hidden")
}
53
2. HTML에서 사용
<div data-controller="toggle">
<button data-action="toggle#toggle">Toggle</button>
<div data-toggle-target="content">
Toggle
</div>
</div>
컨텐츠
54
7.5 Hotwire 장점
빠른 개발: 적은 JavaScript로 동적 UI
자연스러운 UX: SPA 같은 사용자 경험
모바일 최적화: 적은 데이터 전송
유지보수 용이: 서버 중심 로직
55
챕터 8: Gem 활용
8.1 Gem 이란? - Ruby 라이브러리, 재사용 코드 모듈
RubyGems.org: Gem 저장소
Gemfile : Gem 목록 관리
bundle install : Gem 설치
Gem 장점
코드 재사용, 개발 시간 단축
생산성 향상, 풍부한 생태계
56
8.2 유용한 Gem 소개
1. devise : 인증 시스템
# Gemfile
gem 'devise'
설치
#
rails generate devise:install
rails generate devise User
rails db:migrate
# app/models/user.rb
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
end
57
2. kaminari : 페이지네이션
# Gemfile
gem 'kaminari'
컨트롤러
#
@posts = Post.page(params[:page]).per(10)
뷰
#
<%= paginate @posts %>
58
8.2 유용한 Gem 소개 (계속)Gem 활용 팁: RubyGems.org, GitHub 검색 →
Gemfile 추가 → bundle install
59
챕터 9: 배포
9.1 배포 준비
1. Docker Desktop 다운로드
Docker 다운로드
2. 설치 파일 실행 및 지시 사항 따라 설치
3. 설치 완료 후 Docker Desktop 실행
60
9.2 Kamal 배포 config/deploy.yml 설정: 배포 설정
application: myapp
repository:
/myapp
hosts:
_IP_
# ...
서버
계정
주소
4. .env 생성 & 편집
61
9.2 Kamal 배포 Kamal Deploy
dotenv kamal deploy
Kamal 배포 완료! (초기 설정 복잡, 자유도 높음)
62
챕터 10: 마무리
10.1 Rails 강점 복습 - 압도적 생산성, 빠른 개발
풀스택 All-in-one
풍부한 기본 기능 & Gem 생태계
검증된 기술, 유명 서비스 사용
쉬운 유지보수, 깔끔한 구조
Hotwire Modern UI, JS Less
SEO 최적화
Rails = 생산성 + 확장성 + 유지보수성 + Modern Web UI + SEO
63
10.2 다음 단계 학습 가이드 - Rails 공식 가이드 (rails.insomenia.com)
Rails API Document (api.rubyonrails.org)
Ruby Document (ruby-doc.org)
Rails 커뮤니티 (Stack Overflow, Reddit 등)
사이드 프로젝트: 직접 만들어 보세요!
꾸준한 학습, 실습, 커뮤니티 참여 → Rails 전문가
64
10.3 질문 & 답변 - 질문: james@insomenia.com
여러분의 성공적인 웹 서비스 개발을 응원합니다!
Thank you!
65
Download