TIL / 20211017 / RubyOnRails 데이터 전달하기

장정윤·2021년 10월 17일
0

TIL

목록 보기
39/41
post-thumbnail

서버로 데이터 전달하기

params로 추출할 수 있는 데이터
1.POST 방법으로 보낸 데이터
2.쿼리 파라미터
3.라우트 파라미터

form을 통해 데이터를 전달하는 과정

1.view에서 controller로 데이터 전송
2.클라이언트에서 보낸 데이터를 controller에서 추출
3.controller에서 응답한 데이터를 연결된 view에서 출력

Rails 사용한 문법
1.form : htlm에서 서버로 값 전달
2.params: 클라이언트에서 보낸 요청 정보를 controller에서 추출
3.@q변수: 인스턴스 변수, action에서 사용하면 연력된 view에서 사용가능
4.<%= %>: erb파일에서 사용하며, <%= %>안에 ruby 코드 사용가능

CRUD 기능 구현

1.CRUD 모델 생성하기

rails g model [ 모델명 ]

ex) rails g model Post

2.마이그레이션 파일에서 테이블 정보 작성
생성된 마이그레이션 파일에서 테이블 정보 작성

  • title 칼럼과 content 칼럼 만들기
class CreatePosts < ActiveRecord::Migration[5.2]
  def change
    create_table :posts do |t|
		t.string :title
		t.text :content

      t.timestamps
    end
  end
end

3.마이그레이션 파일로 테이블 생성

rake db:migrate

아래처럼 나오면 생성완료

테이블 정보는 db/schema.rb에 담김

Create, Read 하기

  • 페이지 총 3개
    1.index : 모든글을 보는 페이지
    2.new : 글을 작성하는 form이 있는 페이지
    3.show : 하나의 글을 보는 상세 페이지
  • action 총 4개: 1.index, new,create(글을 작성하는 액션),show

내용 정리
@posts = Post.all 코드는 모든 Post 모델의 데이터를 posts로 대입
(모델 클래스의 all 메서드는 SELECT * FROM [테이블명]을 실행 시켜 테이블의 모든 값들을 모델 객체의 배열로 리턴)

p16
Rails는 POST, PUT, DELETE 등 HTTP 메서드로 요청 보낼 때 자동으로 난수화 된 토큰 생성해 전송함
데이터 저장을 요청할 때에는 HTTP 메서드는 get메서드 사용보다 post 메서드 사용이 더 적합

update, destroy 하기

생성할 페이지: form이 포함된 edit 페이지
생성할 action
1.edit
2.update(글 수정)
3.destroy(글 삭제)

destroy는 SQL에서 DELETE FROM [테이블명] WHERE 조건; 쿼리 실행과 동일

전체코드

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"
  post 'posts/update/:id' => "posts#update"
  get 'posts/destroy/:id' => "posts#destroy"
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

posts_controller.rb

class PostsController < ApplicationController
  def index
	  @posts = Post.all
  end

  def new
  end

  def create
	  Post.create(title: params[:title], content: params[:content])
	  redirect_to "/posts/index"
  end

  def show
	  @post = Post.find(params[:id])#:id 값을 추출한 뒤 모델의 find 메서드로 넘어온 id 값을 Post 모델에서 검색하고, 그 결과를 @post에 저장
  end
  def edit
	  @post = Post.find(params[:id])#:id 값을 추출한 뒤 모델의 find 메서드로 넘어온 id 값을 Post 모델에서 검색하고, 그 결과를 @post에 저장
  end
  def update
	  @post = Post.find(params[:id])
	  @post.update(title: params[:title], content: params[:content])
	  redirect_to "/posts/show/#{@post.id}" ##{}안에 변수명을 입력하면 문자열 안에 값이 포함된다
  end
  def destroy
	  @post = Post.find(params[:id])
	  @post.destroy
	  redirect_to "/posts/index"
  end
end

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| %> #@posts 객체 배열 내용 순서대로 출력
		<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>

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>

show.html.erb

<p>
	title : <%= @post.title %>
</p>

<p>
	content : <%= @post.content %>
</p>

<a href="/posts/index">Back</a>

edit.html.erb

<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>
profile
꾸준히 꼼꼼하게 ✉ Email: jjy306105@gmail.com

0개의 댓글