$ rails g model Post
rails g model [모델명]으로 작성된 명령어db/migrate/xxx_create_posts.rbapp/model/post.rbPOST, PostCommentpost.rb, post_comment.rbposts, post_commentsdb/migrate/&&&&&&&_create_posts.rb
class CreatePosts < ActiveRecord::Migration[5.2]
def change
create_table :posts do |t|
t.string :title
t.text :content
t.timestamps
end
end
end
$ rake db:migrate
db/schema.rb
ActiveRecord::Schema.define(version: 2019_09_30_170541) do
create_table "posts", force: :cascade do |t|
t.string "title"
t.text "content"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
ActiveRecord::Schema.define(version: 2019_09_30_170541) do를 통해 version을 확인하면 timestamp가 보이는데 이 부분은 현재 실행된 마이그레이션 파일의 timestamp임$ rails g controller posts index new create show
create는 view가 필요하지 않으므로 app/views/posts/create.html.erb 삭제config/routes.rb
Rails.application.routes.draw do
# root 주소 추가
root 'posts#index'
get 'posts/index'
get 'posts/new'
get 'posts/create'
get 'posts/show'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
root 'posts#index'로 초기 주소 설정app/controllers/post_controller.rb
class PostsController < ApplicationController
def index
@posts = Post.all
end
[...]
end
@posts = Post.all 코드로 모든 Post 모델의 데이터를 @posts로 대입SELECT * FROM [테이블명]을 실행 후 테이블의 모든 값들을 모델 객체의 배열(ActiveRecord_Replation)로 리턴app/views/posts/index.html.erb
<a href="/posts/new">새 글 작성</a>
<hr/>
<table border="1">
<tr>
<th>id</th>
<th>제목</th>
<th>내용</th>
<th>생성일</th>
<th>수정일</th>
</tr>
<% @posts.each do |post| %>
<tr>
<td><%= post.id %></td>
<td><%= post.title %></td>
<td><%= post.content %></td>
<td><%= post.created_at %></td>
<td><%= post.updated_at %></td>
</tr>
<% end %>
</table>
@posts 객체 배열의 내용을 순서대로 출력하기 위해 → each 메서드 사용<%= %> erb 파일에서 Ruby 코드를 실행하지만 출력하지 않을 때 사용 (조건문, 반복문, 변수 할당 등)app/views/posts/new.html.erb
<h4>
새 글 작성
</h4>
<form action="/posts/create" method="POST">
<input name="authenticity_token" value="<%= form_authenticity_token %>" type="hidden">
<input type="text" name="title">
<br/>
<textarea name="content"></textarea>
<button>
제출
</button>
</form>
<input name="authenticity_token" value="<%= form_authenticity_token %>" type="hidden"> 코드는 CSRF 공격을 대응하는 코드CSRFconfig/routes.rb
Rails.application.routes.draw do
get 'posts/index'
get 'posts/new'
post 'posts/create'
get 'posts/show'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
get 'posts/create' 코드를 post 'posts/create'로 변경app/controllers/posts_controller.rb
class PostsController < ApplicationController
[...]
def create
Post.create(title: params[:title], content: params[:content])
redirect_to "/posts/index"
end
[...]
end
Post.create(title: params[:title], content: params[:content]) 코드를 통해서 입력 받은 title과 content의 게시글(Post 모델의 데이터) 생성redirect_to "/posts/index"로 데이터 생성 후 페이지 이동app/views/posts/index.html.erb
<a href="/posts/new">새 글 작성</a>
<hr/>
<table border="1">
<tr>
<th>id</th>
<th>제목</th>
<th>내용</th>
<th>생성일</th>
<th>수정일</th>
<!-- 추가 -->
<th>링크</th>
<!-- 추가 끝 -->
</tr>
<% @posts.each do |post| %>
<tr>
<td><%= post.id %></td>
<td><%= post.title %></td>
<td><%= post.content %></td>
<td><%= post.created_at %></td>
<td><%= post.updated_at %></td>
<!-- 추가 -->
<td><a href="/posts/show/<%= post.id %>">보기</a></td>
<!-- 추가 끝 -->
</tr>
<% end %>
</table>
<a href="/posts/show/<%= [post.id](http://post.id) %>">보기</a>주소를 /posts/show/<%= post.id %>로 설정한 이유config/routes.rb
Rails.application.routes.draw do
get 'posts/index'
get 'posts/new'
post 'posts/create'
# 추가
get 'posts/show/:id' => "posts#show"
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
get 'posts/show/:id' => "posts#show" 코드로 라우트 파리미터 정의routes.rb에서 주소 정의 부분에 ':변수명' 규칙을 지켜 작성posts/:post_id/comments/:comment_id 방식처럼 라우트 파라미터 변수를 여러개 추가하는 것이 가능함app/controllers/posts_controller.rb
class PostsController < ApplicationController
[...]
def show
@post = Post.find(params[:id])
end
end
@post = Post.find(param[:id]) 라이트 파라미터 방식으로 넘어온 :id 값을 param[:id]로 추출params[:id] 는 1이됨@post에 저장find(val) 메서드SELECT * FROM [테이블명] WHERE id=val;을 실행app/views/posts/show.html.erb
<p>
title : <%= @post.title %>
</p>
<p>
content : <%= @post.content %>
</p>
<a href="/posts/index">Back</a>
app/views/posts/index.html.erb
<a href="/posts/new">새 글 작성</a>
<hr/>
<table border="1">
<tr>
<th>id</th>
<th>제목</th>
<th>내용</th>
<th>생성일</th>
<th>수정일</th>
<th>링크</th>
</tr>
<% @posts.each do |post| %>
<tr>
<td><%= post.id %></td>
<td><%= post.title %></td>
<td><%= post.content %></td>
<td><%= post.created_at %></td>
<td><%= post.updated_at %></td>
<td>
<a href="/posts/show/<%= post.id %>">보기</a>
<a href="/posts/edit/<%= post.id %>">수정</a>
</td>
</tr>
<% end %>
</table>
config/routes.rb
Rails.application.routes.draw do
get 'posts/index'
get 'posts/new'
post 'posts/create'
get 'posts/show/:id' => "posts#show"
# 추가
get 'posts/edit/:id' => "posts#edit"
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
app/controllers/posts_controller.rb
class PostsController < ApplicationController
[...]
def edit
@post = Post.find(params[:id])
end
end
@post = Post.find(params[:id])를 통해 특정 게시글을 가져옴app/views/posts/edit.html.rb
<h4>
기존 글 수정
</h4>
<form action="/posts/update/<%= @post.id %>" method="POST">
<input name="authenticity_token" value="<%= form_authenticity_token %>" type="hidden">
<input type="text" name="title" value="<%= @post.title %>">
<br/>
<textarea name="content"><%= @post.content %></textarea>
<button>
수정
</button>
</form>
<input type="text" name="title" value="<%= @post.title %>"> 기존 title 값 추가<textarea name="content"><%= @post.content %></textarea> 기존 content 글 → input과 textarea에 추가config/routes.rb
Rails.application.routes.draw do
[...]
post 'posts/update/:id' => "posts#update"
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
app/controllers/post_controller.rb
class PostsController < ApplicationController
[...]
def update
@post = Post.find(params[:id]) #기존 글 검색
@post.update(title: params[:title], content: params[:content]) #글 수정
redirect_to "/posts/show/#{@post.id}" #수정된 게시글 확인을 위해 이동
end
end
config/routes.rb
Rails.application.routes.draw do
[...]
get 'posts/destroy/:id' => "posts#destroy"
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
app/views/index.html.erb
<a href="/posts/new">새 글 작성</a>
<hr/>
<table border="1">
<tr>
<th>id</th>
<th>제목</th>
<th>내용</th>
<th>생성일</th>
<th>수정일</th>
<th>링크</th>
</tr>
<% @posts.each do |post| %>
<tr>
<td><%= post.id %></td>
<td><%= post.title %></td>
<td><%= post.content %></td>
<td><%= post.created_at %></td>
<td><%= post.updated_at %></td>
<td>
<a href="/posts/show/<%= post.id %>">보기</a>
<a href="/posts/edit/<%= post.id %>">수정</a>
<!-- 코드 추가 -->
<a href="/posts/destroy/<%= post.id %>">삭제</a>
</td>
</tr>
<% end %>
</table>
@post의 데이터를 Post 모델에서 삭제app/controllers/post_controller.rb
class PostsController < ApplicationController
[...]
def destroy
@post = Post.find(params[:id])
@post.destroy
redirect_to "/posts/index"
end
end
DELETE FROM [테이블명] WHERE 조건; 쿼리를 실행하는 것과 같음Reference