Ruby On Rails 이해하기 #4 (CRUD 에러노트)

Michael-Oh·2021년 8월 19일

Ruby On Rails

목록 보기
4/4

레일즈 CRUD 가능한 게시판 만들기 중 에러모음

요약 ;

  • 레일즈앱 만들기
  • 컨트롤러 만들기
  • 모델 만들기
  • index 뷰파일 만들기
  • create 액션만들어서 데이터 저장하기
  • show를 만들기
  • edit/update action만들기
  • delete action 만들기

<에러노트>

Post 모델이 없는 상태에서 Post 데이터를 가져오려고 함.

# 에러발생
에러노트NameError in TestController#index
**uninitialized constant TestController::Post**

# 상황
def index
     @posts = Post.all
end

rake db:migrate 했더니 문제, 이건 migrate에 title과 content가 인식되지 않는 문제

## 에러발생
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

undefined method `title' for #<ActiveRecord::ConnectionAdapters::SQLite3::TableDefinition:0x00007f98467619a8> /Users/ohsekwang/codestates/ruby/r_test/db/migrate/20210804065613_create_posts.rb:4:in`block in change'
/Users/ohsekwang/codestates/ruby/r_test/db/migrate/20210804065613_create_posts.rb:3:in `change'

Caused by:
NoMethodError: undefined method `title' for #<ActiveRecord::ConnectionAdapters::SQLite3::TableDefinition:0x00007f98467619a8> /Users/ohsekwang/codestates/ruby/r_test/db/migrate/20210804065613_create_posts.rb:4:in`block in change'
/Users/ohsekwang/codestates/ruby/r_test/db/migrate/20210804065613_create_posts.rb:3:in `change'

# 문제해결
## mirate 파일에서 입력
### 수정 전
t.title :string
t.content :string

### 수정 후 
t.string :title #t.데이터 타입을 쓰고, :params로 넘겨줄 이름을 쓴다.
t.string :content

라우트 에러 : routes.rb에 post로 설정해놓고, new.erb 파일에서 method를 get를 설정해 놓음

# 에러발생
Routing Error
No route matches [GET] "/create"

# 에러해결
## new.erb 파일 수정
<form action="/create" method="get">
=>  <form action="/create" method="post">

토큰 에러이고, 이유는 보안문제이다. 임시적으로 해결방법으로 해결

## 에러발생
# ActionController::InvalidAuthenticityToken in PracticeController#result
**ActionController::InvalidAuthenticityToken**

## application_controller. rb 파일에 다음을 추가해준다.
skip_before_action :verify_authenticity_token, raise: false
skip_before_filter :verify_authenticity_token, :only => :create

버전 업되면서 사라짐 
=> skip_before_action :verify_authenticity_token, :only => :create

객체 Post에서 id=:post_id 찾을 수 없다.

## 에러 발생
ActiveRecord::RecordNotFound in TestController#show
Couldn't find Post with 'id'=:post_id
Extracted source (around line #18):          

## controller에서 show action
  def show
      @post = Post.find(params[:post_id])
  end

문제해결
## index.erb 버튼에서 수정
<% @posts.each do |post| %> # 
  <%= post.title %> **<a href="/show/:post.id">article 보기</a>**
  <%= post.content %> 
<% end %>

## 버튼의 부분을 수정
<a href="/show/:post.id">article 보기</a>
=><a href="/show/<%=post.id %>">article 보기</a>

에러 : 내용에 해당되는 데이터가 저장되지 않는 문제

  • 에러 화면 이미지 캡쳐

    https://s3-us-west-2.amazonaws.com/secure.notion-static.com/2d517f83-411b-4344-8e80-4dd065ab4e26/Screen_Shot_2021-08-04_at_10.11.33_PM.png

## migrate 파일에서 파일명 확인
t.string :title
t.string **:content**

## new.erb에서 오타 발견
<form action="/create" method="post">
  제목 :<input type="text" name="title" /> <br />
  내용 :<input type="text" **name="centent"** /> <br /> 
  <input type="submit" />
</form>

## 오타 해결
**=> centent => content로**

에러: 토큰 에러, 보안문제, 허용하는 것으로

# 문제발생
## ActionController::InvalidAuthenticityToken in TestController#update

**ActionController::InvalidAuthenticityToken**

## :create 하나만 있었는데, :update도 추가
### 수정전
skip_before_action :verify_authenticity_token, :only => :create
### 수정후
skip_before_action :verify_authenticity_token, :only => :create, **:update**

## 문법오류
SyntaxError
**/Users/ohsekwang/codestates/ruby/r_test/app/controllers/application_controller.rb:2: syntax error, unexpected '\n', expecting =>**
Extracted source (around line **#2**):

## application_controller에서 :update추가
### 수정전
skip_before_action :verify_authenticity_token, :only => **:create, :update**

### 수정후
=>skip_before_action :verify_authenticity_token, :only => **[:create, :update]**

상황별 필기노트 & 에러노트

레일즈앱 만들기

# 터미널 창에서 쓰기 
## 레일즈 앱 처음 만들기
rails new r_test
## r_test 폴더에 들어가기 
cd r_test

컨트롤러 만들기

# 터미널 창에서 test 컨트롤러 만들기
rails g controller test

#VS코드를 실행시키기

## test_controller.rb 파일에서 index 액션 만들기
def index
end

## views의 index.erb 만들기

에러 발생 : Post 모델이 없는 상태에서 Post 데이터를 가져오려고 함.

# 에러발생
에러노트NameError in TestController#index
**uninitialized constant TestController::Post**

# 상황
def index
     @posts = Post.all
end

## 문제해결 모델 만듦

모델 만들기

# 터미널에서 모델 만들기
rails g model Post

## VS코드에서 config폴더에서 migrate 파일를 열고, 데이터 스키마 만들기
t.string :title
t.string :content

#터미널 창에서 DB를 migrate 쓰기
rake db:migrate

에러발생 : rake db:migrate 했더니 문제, 이건 migrate에 title과 content가 인식되지 않는 문제

## 에러발생
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

undefined method `title' for #<ActiveRecord::ConnectionAdapters::SQLite3::TableDefinition:0x00007f98467619a8> /Users/ohsekwang/codestates/ruby/r_test/db/migrate/20210804065613_create_posts.rb:4:in`block in change'
/Users/ohsekwang/codestates/ruby/r_test/db/migrate/20210804065613_create_posts.rb:3:in `change'

Caused by:
NoMethodError: undefined method `title' for #<ActiveRecord::ConnectionAdapters::SQLite3::TableDefinition:0x00007f98467619a8> /Users/ohsekwang/codestates/ruby/r_test/db/migrate/20210804065613_create_posts.rb:4:in`block in change'
/Users/ohsekwang/codestates/ruby/r_test/db/migrate/20210804065613_create_posts.rb:3:in `change'

# 문제해결
## mirate 파일에서 입력
### 수정 전
t.title :string
t.content :string

### 수정 후 
t.string :title #t.데이터 타입을 쓰고, :params로 넘겨줄 이름을 쓴다.
t.string :content

index 뷰파일 만들기 중

index 뷰파일 실행 안됨
<% @posts.each do |post| %> # 
  <%= post.title %>
  <%= post.content %> 
<% end %>

## create action을 만들지 않아 데이터 저장이 안됨

create 만들어서 데이터 저장하기

#컨트롤러에서 액션 만들기
def create
      post = Post.new
      post.title = params[:title]
      post.content = params[:content]
      post.save
      redirect_to '/'
end

## routes.rb 추가
post '/create' => 'test#create'

## new.erb 파일 수정
<form action="/" method="get"> 
=>  <form action="/create" method="get">

라우트 에러 : routes.rb에 post로 설정해놓고, new.erb 파일에서 method를 get를 설정해 놓음

# 에러발생
Routing Error
No route matches [GET] "/create"

# 에러해결
## new.erb 파일 수정
<form action="/create" method="get">
=>  <form action="/create" method="post">

에러노트 : 토큰 에러이고, 이유는 보안문제이다. 임시적으로 해결방법으로 해결

## 에러발생
# ActionController::InvalidAuthenticityToken in PracticeController#result
**ActionController::InvalidAuthenticityToken**

## application_controller. rb 파일에 다음을 추가해준다.
skip_before_action :verify_authenticity_token, raise: false
skip_before_filter :verify_authenticity_token, :only => :create

버전 업되면서 사라짐 
=> skip_before_action :verify_authenticity_token, :only => :create

show를 만들기 중

# index에서 show article 버튼 만들기
<a href="/show/:post_id">article 보기</a>

## controller show action
def show
     @post = Post.find(params[:post_id])
end

# routes.rb
get '/show/:post_id' => 'test#show'

## show.erb
주제:<%= @post.title %> <br>
내용:<%= @post.content %> <hr>

에러 : 객체 Post에서 id=:post_id 찾을 수 없다.

## 에러 발생
ActiveRecord::RecordNotFound in TestController#show
Couldn't find Post with 'id'=:post_id
Extracted source (around line #18):          

## controller에서 show action
  def show
      @post = Post.find(params[:post_id])
  end

문제해결
## index.erb 버튼에서 수정
<% @posts.each do |post| %> # 
  <%= post.title %> **<a href="/show/:post.id">article 보기</a>**
  <%= post.content %> 
<% end %>

## 버튼의 부분을 수정
<a href="/show/:post.id">article 보기</a>
=><a href="/show/<%=post.id %>">article 보기</a>

에러 : 내용에 해당되는 데이터가 저장되지 않는 문제

  • 에러 화면 이미지 캡쳐

## migrate 파일에서 파일명 확인
t.string :title
t.string **:content**

## new.erb에서 오타 발견
<form action="/create" method="post">
  제목 :<input type="text" name="title" /> <br />
  내용 :<input type="text" **name="centent"** /> <br /> 
  <input type="submit" />
</form>

## 오타 해결
**=> centent => content로**

edit 만들기

##index.erb 수정버튼
<a href="/edit/<%=post.id %>">article 수정</a> <br />

## controller edit 액션만들기
def edit
      @post = Post.find(params[:post_id])
end

## edit.erb 파일
<form action="/update/<%=@post.id%>" method="post"> #update액션에 연결되도록
  <input type="text" name="title" value="<%=@post.title%>" />
  <input type="text" name="content" value="<%=@post.title%>" />
  <input type="submit" />
</form>

## controller update 추가
def update
      post = Post.find(params[:post_id])
      post.title = params[:title]
      post.content = params[:content]
      post.save
      redirect_to :back => redirect_back(fallback_location: root_path)
  end

## routes.rb edit와 update url과 action 연결
get '/edit/:post_id' => 'test#edit'
post '/update/:post_id' => 'test#update'

에러: 토큰 에러, 보안문제, 허용하는 것으로

# 문제발생
## ActionController::InvalidAuthenticityToken in TestController#update

**ActionController::InvalidAuthenticityToken**

## :create 하나만 있었는데, :update도 추가
### 수정전
skip_before_action :verify_authenticity_token, :only => :create
### 수정후
skip_before_action :verify_authenticity_token, :only => :create, **:update**

## 문법오류
SyntaxError
**/Users/ohsekwang/codestates/ruby/r_test/app/controllers/application_controller.rb:2: syntax error, unexpected '\n', expecting =>**
Extracted source (around line **#2**):

## application_controller에서 :update추가
### 수정전
skip_before_action :verify_authenticity_token, :only => **:create, :update**

### 수정후
=>skip_before_action :verify_authenticity_token, :only => **[:create, :update]**

delete액션 만들기 중

## controller에서 delete action 만들기
def delete
		Post.destroy(params[:post_id)
		redirect_to '/'
end
## index.erb
<a herf='/delete/<%=post.id %>'>article삭제 </a>

## routes.rb
get '/delete/:post_id' => 'test#delete'
profile
초보 개발자의 테니스 과학적 분석 Dev-Log

0개의 댓글